How can I convert a date in YYYYMMDDHHMMSS format to epoch or unix time?

前端 未结 2 1928
迷失自我
迷失自我 2020-12-22 00:58

EDIT: I have edited my question to include more information, I have tried many ways to do this already, asking a question on StackOverflow is usually my last resort. Any hel

相关标签:
2条回答
  • 2020-12-22 01:25

    tl;dr

    LocalDateTime
    .parse(
        "20140430193247" , 
        DateTimeFormatter.ofPattern( "uuuuMMddHHmmss" )
    )
    .atOffset(
        ZoneOffset.UTC
    )
    .toEpochSecond()
    

    java.time

    Parse your input string as a LocalDateTime as it lacks an indicator of offset-from-UTC or time zone.

    String input = "20140430193247" ;
    DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuuMMddHHmmss" ) ;
    LocalDateTime ldt = LocalDateTime.parse( input , f ) ;
    

    Now we have a date with time-of-day, around half-past 7 PM on April 30 of 2014. But we lack the context of offset/zone. So we do not know if this was 7 PM in Tokyo Japan or 7 PM in Toledo Ohio US, two different moments that happened several hours apart.

    To determine a moment, you must know the intended offset/zone.

    If you know for certain that an offset of zero, or UTC itself, was intended, apply the constant ZoneOffset.UTC to get an OffsetDateTime.

    OffsetDateTime odt = ldt.atOffset( ZoneOffset.UTC ) ;
    

    How can I convert this into Epoch/Unix time?

    Do you mean a count of seconds or milliseconds since the first moment of 1970 in UTC?

    For a count of whole seconds since 1970-01-01T00:00Z, interrogate the OffsetDateTime object.

    long secondsSinceEpoch = odt.toEpochSecond() ;
    

    For milliseconds, extract a Instant object. An Instant represents a moment in UTC, and is the basic building-block class of java.time. Then interrogate for the count.

    Instant instant = odt.toInstant() ; 
    long millisSinceEpoch = instant.toEpochMilli() ;
    
    0 讨论(0)
  • 2020-12-22 01:40

    I got the answer after quite a while of trying different ways. The solution was pretty simple - to parse the time to a string as toString() didn't work.

        Date date;
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
    
        try {
            date = df.parse(String.valueOf(_time.getTime()));
        } catch (ParseException e) {
            throw new RuntimeException("Failed to parse date: ", e);
        }
    
        return date.getTime();
    
    0 讨论(0)
提交回复
热议问题