开发者

How can I convert this date in Java?

I want to convert:

2010-03开发者_JAVA百科-15T16:34:46Z

into something like "5 hours ago"

How can I do this in Java?


JodaTime supports parsing from a user-defined format. See DateTimeFormatterBuilder and DateTimeBuilder.parseDateTime().

Once you have a DateTime, you can create a Duration or Period from that and the current time, and use another formatter to pretty-print. [See the PeriodFormatter example referenced by BalusC in comments above.]


I know a plugin in Jquery for this : http://plugins.jquery.com/project/CuteTime

For Java i assume you will need to use your brain :) ( You can translate it to Java )


     Calendar calendar = new GregorianCalendar(2010,Calendar.March,15, 16,34,46);
     calendar.add(Calendar.HOUR,-5);


tl;dr

Duration.between(
    Instant.parse( "2010-03-15T16:34:46Z" ) , 
    Instant.now() 
)     
.toHours()    // returns a `long` integer number. 
+ " hours ago"

5 hours ago

java.time

The modern approach uses the java.time classes that supplant the troublesome old legacy date-time classes.

Instant

Parse your input string. That string uses a format defined in the ISO 8601 standard. The java.time classes use these standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.

Instant instant = Instant.parse( "2010-03-15T16:34:46Z" ) ;

Get our later moment.

Instant later = instant.now() ;  // Capture the current moment in UTC.

Let’s use an moment five hour later.

Instant later = instant.plus( 5L , ChronoUnit.HOURS ) ;

Duration

Represent elapsed time of hours-minutes-seconds with Duration class.

Duration d = Duration.between( instant , later ) ;

If you want to report the entire elapsed time as one big number of hours, call Duration::toHours.

String output = d.toHoursPart() + " hours ago" ;

5 hours ago

In Java 9 and later, call to…Part to get each part of days, hours, minutes, seconds, nanoseconds. These methods were strangely missing in Java 8, but added in Java 9 and later.

long daysPart = d.toDaysPart() ;
int hoursPart = d.toHoursPart() ;
int minutesPart = d.toMinutesPart() ;
String output = … ;  // Use the parts to generate your output.

ISO 8601 duration

You may find the ISO 8601 compliant string for durations generated by Duration::toString to be useful: PnYnMnDTnHnMnS

The P marks the beginning. The T separates any years-months-days from any hours-minutes-seconds.

So our example above for five hours would be:

PT5H

Such strings can be parsed into Duration hours.

Duration d = Duration.parse( "PT5H" ) ;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜