如何用Java计算时间跨度并格式化输出?
我想用两次时间(从纪元算起,以秒为单位)显示两种格式之间的差异,如:如何用Java计算时间跨度并格式化输出?,java,date,time,formatting,Java,Date,Time,Formatting,我想用两次时间(从纪元算起,以秒为单位)显示两种格式之间的差异,如: 2分钟 1小时15分钟 3小时9分钟 一分钟前 1小时2分钟前 我怎样才能做到这一点呢?我不是Java专家,但你可以做t1-t2=t3(以秒为单位),然后除以60,得到分钟,再除以60,得到秒。然后,只需计算出您需要多少个部门 希望能有帮助。我总是从一开始。在Java中处理日期和时间总是“有趣”的,但Joda Time可以减轻压力 他们有间隔和持续时间课程,完成了你所寻找的一半。但不确定它们是否有以可读格式输出的函数。我会
- 2分钟
- 1小时15分钟
- 3小时9分钟
- 一分钟前
- 1小时2分钟前
我怎样才能做到这一点呢?我不是Java专家,但你可以做t1-t2=t3(以秒为单位),然后除以60,得到分钟,再除以60,得到秒。然后,只需计算出您需要多少个部门 希望能有帮助。我总是从一开始。在Java中处理日期和时间总是“有趣”的,但Joda Time可以减轻压力 他们有间隔和持续时间课程,完成了你所寻找的一半。但不确定它们是否有以可读格式输出的函数。我会继续找的 HTH这门课可以处理大多数与日期相关的数学。不过,您必须自己获得结果并输出格式。没有一个标准库可以完全满足您的需求,尽管可能有第三方库可以做到这一点
long time1, time2;
time1 = System.currentMillis();
.. drink coffee
time2 = System.currentMillis();
long difference = time2 - time1 // millies between time1 and time2
java.util.Date differneceDate = new Date(difference);
要创建类似“2分钟”的字符串,应使用DateFormatter/DateFormat。您可以在JavaAPI规范(Java.sun.com)中找到关于这方面的更多详细信息 我建议您查看一下好的,在简要阅读了API之后,您似乎可以执行以下操作:-
HTH如果您的时间跨越夏令时(夏季)边界,是否要报告天数 例如,第二天的23:00到23:00始终是一天,但可能是23、24或25小时,具体取决于您是否通过夏令时转换
如果你关心这一点,请确保将其纳入你的选择。是的,唤醒了我的死者,但这是我基于@mtim posted代码的改进实现,因为该线程几乎位于搜索的顶部,所以我正在与sleepy hollow混在一起
public static String getFriendlyTime(Date dateTime) {
StringBuffer sb = new StringBuffer();
Date current = Calendar.getInstance().getTime();
long diffInSeconds = (current.getTime() - dateTime.getTime()) / 1000;
/*long diff[] = new long[]{0, 0, 0, 0};
/* sec * diff[3] = (diffInSeconds >= 60 ? diffInSeconds % 60 : diffInSeconds);
/* min * diff[2] = (diffInSeconds = (diffInSeconds / 60)) >= 60 ? diffInSeconds % 60 : diffInSeconds;
/* hours * diff[1] = (diffInSeconds = (diffInSeconds / 60)) >= 24 ? diffInSeconds % 24 : diffInSeconds;
/* days * diff[0] = (diffInSeconds = (diffInSeconds / 24));
*/
long sec = (diffInSeconds >= 60 ? diffInSeconds % 60 : diffInSeconds);
long min = (diffInSeconds = (diffInSeconds / 60)) >= 60 ? diffInSeconds % 60 : diffInSeconds;
long hrs = (diffInSeconds = (diffInSeconds / 60)) >= 24 ? diffInSeconds % 24 : diffInSeconds;
long days = (diffInSeconds = (diffInSeconds / 24)) >= 30 ? diffInSeconds % 30 : diffInSeconds;
long months = (diffInSeconds = (diffInSeconds / 30)) >= 12 ? diffInSeconds % 12 : diffInSeconds;
long years = (diffInSeconds = (diffInSeconds / 12));
if (years > 0) {
if (years == 1) {
sb.append("a year");
} else {
sb.append(years + " years");
}
if (years <= 6 && months > 0) {
if (months == 1) {
sb.append(" and a month");
} else {
sb.append(" and " + months + " months");
}
}
} else if (months > 0) {
if (months == 1) {
sb.append("a month");
} else {
sb.append(months + " months");
}
if (months <= 6 && days > 0) {
if (days == 1) {
sb.append(" and a day");
} else {
sb.append(" and " + days + " days");
}
}
} else if (days > 0) {
if (days == 1) {
sb.append("a day");
} else {
sb.append(days + " days");
}
if (days <= 3 && hrs > 0) {
if (hrs == 1) {
sb.append(" and an hour");
} else {
sb.append(" and " + hrs + " hours");
}
}
} else if (hrs > 0) {
if (hrs == 1) {
sb.append("an hour");
} else {
sb.append(hrs + " hours");
}
if (min > 1) {
sb.append(" and " + min + " minutes");
}
} else if (min > 0) {
if (min == 1) {
sb.append("a minute");
} else {
sb.append(min + " minutes");
}
if (sec > 1) {
sb.append(" and " + sec + " seconds");
}
} else {
if (sec <= 1) {
sb.append("about a second");
} else {
sb.append("about " + sec + " seconds");
}
}
sb.append(" ago");
/*String result = new String(String.format(
"%d day%s, %d hour%s, %d minute%s, %d second%s ago",
diff[0],
diff[0] > 1 ? "s" : "",
diff[1],
diff[1] > 1 ? "s" : "",
diff[2],
diff[2] > 1 ? "s" : "",
diff[3],
diff[3] > 1 ? "s" : ""));*/
return sb.toString();
}
公共静态字符串getFriendlyTime(日期时间){
StringBuffer sb=新的StringBuffer();
当前日期=Calendar.getInstance().getTime();
long diffinsionds=(current.getTime()-dateTime.getTime())/1000;
/*long diff[]=新的long[]{0,0,0,0};
/*sec*diff[3]=(diffInSeconds>=60?diffInSeconds%60:diffInSeconds);
/*min*diff[2]=(diffinsectonds=(diffinsectonds/60))>=60?diffinsectonds%60:diffinsectonds;
/*小时数*diff[1]=(diffinsectonds=(diffinsectonds/60))>=24?diffinsectonds%24:diffinsectonds;
/*天数*diff[0]=(diffinsectonds=(diffinsectonds/24));
*/
长秒=(diffinsectonds>=60?diffinsectonds%60:diffinsectonds);
long min=(diffinsectonds=(diffinsectonds/60))>=60?diffinsectonds%60:diffinsectonds;
长时间=(diffinsectonds=(diffinsectonds/60))>=24?diffinsectonds%24:diffinsectonds;
长天数=(diffinsectonds=(diffinsectonds/24))>=30?diffinsectonds%30:diffinsectonds;
长月份=(diffinsectonds=(diffinsectonds/30))>=12?diffinsectonds%12:diffinsectonds;
长年=(diffunseconds=(diffunseconds/12));
如果(年数>0){
如果(年=1){
某人追加(“一年”);
}否则{
某人追加(年+年);
}
如果(第0年){
如果(月=1){
某人追加(“和一个月”);
}否则{
sb.附加(“和”+月+“月”);
}
}
}否则,如果(月数>0){
如果(月=1){
某人追加(“一个月”);
}否则{
sb.追加(月+月);
}
如果(第0个月){
如果(天数==1){
某人附加(“和一天”);
}否则{
某人附加(“和”+天+“天”);
}
}
}否则如果(天数>0){
如果(天数==1){
某人附加(“一天”);
}否则{
某人追加(天+“天”);
}
如果(第0天){
如果(小时=1){
某人追加(“和一小时”);
}否则{
sb.附加(“和”+hrs+“小时”);
}
}
}否则,如果(小时数>0){
如果(小时=1){
某人追加(“一小时”);
}否则{
某人追加(小时数+小时数);
}
如果(最小值>1){
某人附加(“和”+min+“分钟”);
}
}否则,如果(最小值>0){
如果(最小==1){
某人追加(“一分钟”);
}否则{
某人追加(分钟+“分钟”);
}
如果(秒>1){
某人附加(“和”+秒+“秒”);
}
}否则{
如果(第1节“s”):,
diff[1],
差异[1]>1?“:”,
diff[2],
差异[2]>1?“:”,
diff[3],
差异[3]>1?“:”)*/
使某人返回字符串();
}
它显然是可以改进的。基本上,它试图使时间跨度更友好,但有一些限制,即如果时间(参数)是在将来,它会表现得很奇怪,并且它仅限于天、小时和秒(不处理月和年,以便其他人可以;-)
样本输出为:
- 大约一秒钟前
- 8分34秒前
- 一小时零四分钟前
- 一天前
- 29天前
- 一年零三个月前
public static String getFriendlyTime(Date dateTime) {
StringBuffer sb = new StringBuffer();
Date current = Calendar.getInstance().getTime();
long diffInSeconds = (current.getTime() - dateTime.getTime()) / 1000;
/*long diff[] = new long[]{0, 0, 0, 0};
/* sec * diff[3] = (diffInSeconds >= 60 ? diffInSeconds % 60 : diffInSeconds);
/* min * diff[2] = (diffInSeconds = (diffInSeconds / 60)) >= 60 ? diffInSeconds % 60 : diffInSeconds;
/* hours * diff[1] = (diffInSeconds = (diffInSeconds / 60)) >= 24 ? diffInSeconds % 24 : diffInSeconds;
/* days * diff[0] = (diffInSeconds = (diffInSeconds / 24));
*/
long sec = (diffInSeconds >= 60 ? diffInSeconds % 60 : diffInSeconds);
long min = (diffInSeconds = (diffInSeconds / 60)) >= 60 ? diffInSeconds % 60 : diffInSeconds;
long hrs = (diffInSeconds = (diffInSeconds / 60)) >= 24 ? diffInSeconds % 24 : diffInSeconds;
long days = (diffInSeconds = (diffInSeconds / 24)) >= 30 ? diffInSeconds % 30 : diffInSeconds;
long months = (diffInSeconds = (diffInSeconds / 30)) >= 12 ? diffInSeconds % 12 : diffInSeconds;
long years = (diffInSeconds = (diffInSeconds / 12));
if (years > 0) {
if (years == 1) {
sb.append("a year");
} else {
sb.append(years + " years");
}
if (years <= 6 && months > 0) {
if (months == 1) {
sb.append(" and a month");
} else {
sb.append(" and " + months + " months");
}
}
} else if (months > 0) {
if (months == 1) {
sb.append("a month");
} else {
sb.append(months + " months");
}
if (months <= 6 && days > 0) {
if (days == 1) {
sb.append(" and a day");
} else {
sb.append(" and " + days + " days");
}
}
} else if (days > 0) {
if (days == 1) {
sb.append("a day");
} else {
sb.append(days + " days");
}
if (days <= 3 && hrs > 0) {
if (hrs == 1) {
sb.append(" and an hour");
} else {
sb.append(" and " + hrs + " hours");
}
}
} else if (hrs > 0) {
if (hrs == 1) {
sb.append("an hour");
} else {
sb.append(hrs + " hours");
}
if (min > 1) {
sb.append(" and " + min + " minutes");
}
} else if (min > 0) {
if (min == 1) {
sb.append("a minute");
} else {
sb.append(min + " minutes");
}
if (sec > 1) {
sb.append(" and " + sec + " seconds");
}
} else {
if (sec <= 1) {
sb.append("about a second");
} else {
sb.append("about " + sec + " seconds");
}
}
sb.append(" ago");
/*String result = new String(String.format(
"%d day%s, %d hour%s, %d minute%s, %d second%s ago",
diff[0],
diff[0] > 1 ? "s" : "",
diff[1],
diff[1] > 1 ? "s" : "",
diff[2],
diff[2] > 1 ? "s" : "",
diff[3],
diff[3] > 1 ? "s" : ""));*/
return sb.toString();
}
DateTime myBirthDate = new DateTime(1978, 3, 26, 12, 35, 0, 0);
DateTime now = new DateTime();
Period period = new Period(myBirthDate, now);
PeriodFormatter formatter = new PeriodFormatterBuilder()
.appendYears().appendSuffix(" year, ", " years, ")
.appendMonths().appendSuffix(" month, ", " months, ")
.appendWeeks().appendSuffix(" week, ", " weeks, ")
.appendDays().appendSuffix(" day, ", " days, ")
.appendHours().appendSuffix(" hour, ", " hours, ")
.appendMinutes().appendSuffix(" minute, ", " minutes, ")
.appendSeconds().appendSuffix(" second", " seconds")
.printZeroNever()
.toFormatter();
String elapsed = formatter.print(period);
System.out.println(elapsed + " ago");
32 years, 1 month, 1 week, 5 days, 6 hours, 56 minutes, 24 seconds ago
SimpleDateFormat curFormater = new SimpleDateFormat("EEE, dd MMM yyyy kk:mm:ss");
try {
Date dateObj = curFormater.parse(pubDate);
SimpleDateFormat postFormater = new SimpleDateFormat("MMMM dd, yyyy ss:mm:hh");
String newDateStr = postFormater.format(dateObj);
Log.v("THE NEW DATE IS",newDateStr);
long pubdateinmilis = dateObj.getTime();
pubDate = (String) DateUtils.getRelativeTimeSpanString(pubdateinmilis, System.currentTimeMillis(),DateUtils.HOUR_IN_MILLIS,DateUtils.FORMAT_ABBREV_RELATIVE);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SimpleDateFormat ymdhms=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
DecimalFormat formatter = new DecimalFormat("#,###"); /* ("#,###.00"); gives you the decimal fractions */
int counter=0;
Date beginTime0=new Date();
while (<some end condition>) {
<some time consuming operation>
/*// uncomment this section durring initial exploration of the time consumer
if(counter>100000){
System.out.println("debug exiting due to counter="+counter);
System.exit(0);
}
*/
if(0==counter%1000){
Date now = new Date();
long diffInSeconds = (now.getTime() - beginTime0.getTime()) / 1000;
long diff[] = new long[] { 0, 0, 0, 0 };
diff[3] = (diffInSeconds >= 60 ? diffInSeconds % 60 : diffInSeconds); /* sec */
diff[2] = (diffInSeconds = (diffInSeconds / 60)) >= 60 ? diffInSeconds % 60 : diffInSeconds; /* min */
diff[1] = (diffInSeconds = (diffInSeconds / 60)) >= 24 ? diffInSeconds % 24 : diffInSeconds; /* hours */
diff[0] = (diffInSeconds = (diffInSeconds / 24)); /* days */
String delta = String.format(
"%s%s%s%s"
,(diff[0]>0?String.format("%d day%s " ,diff[0],(diff[0]!=1?"s":"")):"")
,(diff[1]>0?String.format("%2d hour%s " ,diff[1],(diff[1]!=1?"s":" ")):"")
,(diff[2]>0?String.format("%2d minute%s ",diff[2],(diff[2]!=1?"s":" ")):"")
, String.format("%2d second%s ",diff[3],(diff[3]!=1?"s":" "))
);
System.out.println(String.format(
"%12s %s delta= %s"
,formatter.format(counter)
,ymdhms.format(new Date())
,delta
)
);
}
counter++;
}
System.out.println(p.format(new Date(System.currentTimeMillis() + 1000*60*10)));
//prints: "10 minutes from now"
public static void main(String[] args) throws IOException, ParseException {
String since = "2017-02-24T04:44:05.601Z";
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
TimeZone utc = TimeZone.getTimeZone("UTC");
dateFormat.setTimeZone(utc);
Date sinceDate = dateFormat.parse(since);
Date now = new Date();
long durationInSeconds = TimeUnit.MILLISECONDS.toSeconds(now.getTime() - sinceDate.getTime());
long SECONDS_IN_A_MINUTE = 60;
long MINUTES_IN_AN_HOUR = 60;
long HOURS_IN_A_DAY = 24;
long DAYS_IN_A_MONTH = 30;
long MONTHS_IN_A_YEAR = 12;
long sec = (durationInSeconds >= SECONDS_IN_A_MINUTE) ? durationInSeconds % SECONDS_IN_A_MINUTE : durationInSeconds;
long min = (durationInSeconds /= SECONDS_IN_A_MINUTE) >= MINUTES_IN_AN_HOUR ? durationInSeconds%MINUTES_IN_AN_HOUR : durationInSeconds;
long hrs = (durationInSeconds /= MINUTES_IN_AN_HOUR) >= HOURS_IN_A_DAY ? durationInSeconds % HOURS_IN_A_DAY : durationInSeconds;
long days = (durationInSeconds /= HOURS_IN_A_DAY) >= DAYS_IN_A_MONTH ? durationInSeconds % DAYS_IN_A_MONTH : durationInSeconds;
long months = (durationInSeconds /=DAYS_IN_A_MONTH) >= MONTHS_IN_A_YEAR ? durationInSeconds % MONTHS_IN_A_YEAR : durationInSeconds;
long years = (durationInSeconds /= MONTHS_IN_A_YEAR);
String duration = getDuration(sec,min,hrs,days,months,years);
System.out.println(duration);
}
private static String getDuration(long secs, long mins, long hrs, long days, long months, long years) {
StringBuffer sb = new StringBuffer();
String EMPTY_STRING = "";
sb.append(years > 0 ? years + (years > 1 ? " years " : " year "): EMPTY_STRING);
sb.append(months > 0 ? months + (months > 1 ? " months " : " month "): EMPTY_STRING);
sb.append(days > 0 ? days + (days > 1 ? " days " : " day "): EMPTY_STRING);
sb.append(hrs > 0 ? hrs + (hrs > 1 ? " hours " : " hour "): EMPTY_STRING);
sb.append(mins > 0 ? mins + (mins > 1 ? " mins " : " min "): EMPTY_STRING);
sb.append(secs > 0 ? secs + (secs > 1 ? " secs " : " secs "): EMPTY_STRING);
sb.append("ago");
return sb.toString();
}
Instant start = Instant.ofEpochSecond( … );
Instant stop = Instant.ofEpochSecond( … );
Instant start = Instant.now() ;
Instant stop = start.plusSeconds( TimeUnit.MINUTES.toSeconds( 7L ) ) ; // Seven minutes as a number of seconds.
Duration duration = Duration.between( start , stop );
String outputStandard = duration.toString();
int days = duration.toDaysPart() ;
int hours = duration.toHoursPart() ;
int minutes = duration.toMinutesPart() ;
int seconds = duration.toSecondsPart() ;
int nanos = duration.toNanosPart() ;
StringBuilder sb = new StringBuilder( 100 );
if( days != 0 ) {
sb.append( days + " days" ) ;
};
if( hours != 0 ) {
sb.append( ( sb.length = 0 ) ? ( "" ) : ( ", " ) ) ; // Append comma if any existing text.
sb.append( hours + " hours" ) ;
};
if( minutes != 0 ) {
sb.append( ( sb.length = 0 ) ? ( "" ) : ( ", " ) ) ; // Append comma if any existing text.
sb.append( minutes + " minutes" ) ;
};
if( seconds != 0 ) {
sb.append( ( sb.length = 0 ) ? ( "" ) : ( ", " ) ) ; // Append comma if any existing text.
sb.append( seconds + " seconds" ) ;
};
if( nanos != 0 ) {
sb.append( ( sb.length = 0 ) ? ( "" ) : ( ", " ) ) ; // Append comma if any existing text.
sb.append( nanos + " nanos" ) ;
};
String output = sb.toString();
dateHere.setText(DateUtils.getRelativeTimeSpanString(timeInMillis,
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS));
import java.time.Duration;
import java.time.Instant;
class Main {
public static void main(String[] args) {
// Test
System.out.println(getFormattedDuration(1619575035, 1619810961));
}
public static String getFormattedDuration(long start, long end) {
Instant startInstant = Instant.ofEpochSecond(start);
Instant endInstant = Instant.ofEpochSecond(end);
Duration duration = Duration.between(startInstant, endInstant);
// Custom format
// ####################################Java-8####################################
return String.format("%d days, %d hours, %d minutes, %d seconds", duration.toDays(), duration.toHours() % 24,
duration.toMinutes() % 60, duration.toSeconds() % 60);
// ##############################################################################
// ####################################Java-9####################################
// return String.format("%d days, %d hours, %d minutes, %d seconds",
// duration.toDaysPart(), duration.toHoursPart(),
// duration.toMinutesPart(), duration.toSecondsPart());
// ##############################################################################
}
}
2 days, 17 hours, 32 minutes, 6 seconds