White Shadows
White Shadows

Reputation: 139

Convert String to epoch

I have a string - 20180915 in format yyyyMMdd I need to get epoch milli seconds for this date, answer for 20180915 should be 1537012800000

I was able to do this using following function -

import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
public static void main(String args[]) throws ParseException {

        String myDate = "2018-09-15 12:00:00";
        LocalDateTime localDateTime = LocalDateTime.parse(myDate,
                DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") );
        System.out.println(localDateTime);
        long millis = localDateTime
                .atZone(ZoneOffset.UTC)
                .toInstant().toEpochMilli();
        System.out.println(millis);
    }

The problem I am facing is - I am passing String as "2018-09-15 12:00:00" but my input is "20180915". I am unable to find good way to convert "20180915" to "2018-09-15 12:00:00" How can i achieve this ?

Upvotes: 2

Views: 1971

Answers (3)

Andreas
Andreas

Reputation: 159086

You can make the DateTimeFormatter do all the work, which is especially useful if you need to parse multiple dates, as it reduces the number of intermediate parsing steps (and objects created):

DateTimeFormatter fmt = new DateTimeFormatterBuilder()
        .appendPattern("uuuuMMdd")
        .parseDefaulting(ChronoField.HOUR_OF_DAY, 12)
        .toFormatter()
        .withZone(ZoneOffset.UTC);

String input = "20180915";
long epochMilli = OffsetDateTime.parse(input, fmt).toInstant().toEpochMilli();
System.out.println(epochMilli); // prints: 1537012800000

You can replace OffsetDateTime with ZonedDateTime. Makes no difference to the result.

Upvotes: 3

White Shadows
White Shadows

Reputation: 139

Answer -

private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");

public static Long getMillisForDate(String date) {
    return LocalDateTime
            .of(LocalDate.parse(date, formatter), LocalTime.NOON)
            .atZone(ZoneOffset.UTC)
            .toInstant().toEpochMilli();
}

Upvotes: 3

Deian
Deian

Reputation: 1374

Parse the date with proper mask "yyyyMMdd"

SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
Date date = format.parse("20180915");
long epochs = date.getTime();

Upvotes: 0

Related Questions