LocalTime from Date

后端 未结 4 1882
有刺的猬
有刺的猬 2020-12-18 23:09

I\'m trying to convert a Date instance to a LocalTime instance.

// Create the Date
Date date = format.parse(\"2011-02-18 05:00:00.0         


        
4条回答
  •  有刺的猬
    2020-12-18 23:46

    The accepted Answer by Jon Skeet is correct. This Answer expands on those ideas.

    Avoid legacy date-time classes

    Some of the other Answers, and the Question, mix the old legacy date-time classes with the new. That is unnecessary and bad practice. The whole point of the java.time classes is to replace the troublesome and confusing old classes.

    • You do not need java.util.Date.
    • You do not need java.util.Calendar.

    LocalDateTime

    Your input string lacks any information about offset-from-UTC or time zone. So we parse it as a LocalDateTime object.

    To parse, we replace the SPACE in the middle with a T to comply with the ISO 8601 standard for date-time formats.

    String input = "2011-02-18 05:00:00.0".replace( " " , "T" );
    LocalDateTime ldt = LocalDateTime.parse( input );
    

    LocalTime

    To focus on the time-of-day without the date, ask for a LocalTime.

    LocalTime lt = ldt.toLocalTime();
    

    ZonedDateTime

    Note that none of this are actual moments, not a point on the timeline. Without the context of an offset-from-UTC or a time zone, we do not know if you meant 5 AM in Auckland NZ or 5 AM in Kolkata IN or 5 AM in Paris France or 5 AM in Montréal Québec. Each of those would be very different moments in time.

    If by context you do know for certain the intended time zone, apply it. Apply a ZoneId to get a ZonedDateTime.

    ZoneId z = ZoneId.of( "America/Montreal" );
    ZonedDateTime zdt = ldt.atZone( z );
    

    From there, ask for the LocalTime if desired.

    LocalTime lt = zdt.toLocalTime(); 
    

    Instant

    If you want to see that same moment in UTC, extract an Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

    Generally best to focus on UTC in much of your business logic, logging, data storage, and data exchange. Learn to think of UTC as “The One True Time”.

    Instant instant = zdt.toInstant();  // Same moment, shifted to UTC.
    

提交回复
热议问题