How can I convert this date in Java?

2019-01-28 17:13发布

I want to convert:

2010-03-15T16:34:46Z

into something like "5 hours ago"

How can I do this in Java?

4条回答
看我几分像从前
2楼-- · 2019-01-28 17:51

tl;dr

Duration.between(
    Instant.parse( "2010-03-15T16:34:46Z" ) , 
    Instant.now() 
)     
.toHoursPart()    // returns a `int` 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 ) ;

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.

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

5 hours ago

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" ) ;
查看更多
唯我独甜
3楼-- · 2019-01-28 17:55

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 )

查看更多
叛逆
4楼-- · 2019-01-28 17:59

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.]

查看更多
Lonely孤独者°
5楼-- · 2019-01-28 18:12
     Calendar calendar = new GregorianCalendar(2010,Calendar.March,15, 16,34,46);
     calendar.add(Calendar.HOUR,-5);
查看更多
登录 后发表回答