2

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 ?

Harry Coder
  • 2,429
  • 2
  • 28
  • 32
White Shadows
  • 139
  • 1
  • 2
  • 12
  • You need to add two `-` to the String as `yyyy` can mean 4 or more digits. i.e. it doesn't stop at 4. – Peter Lawrey Oct 01 '18 at 19:15
  • Parse it as a LocalDate, using the correct pattern, then change the LocalDate to a LocalDateTime by setting the time to MIDNIGHT. – JB Nizet Oct 01 '18 at 19:15
  • I wonder why you post this as a comment and not an answer. I'd've upvoted it, @JBNizet – iajrz Oct 01 '18 at 19:18
  • @iajrz The optimistic part of me is hoping that the OP will try doing it by himself. – JB Nizet Oct 01 '18 at 19:24
  • @JB Nizet Thanks. I have updated the answer. – White Shadows Oct 01 '18 at 19:26
  • 1
    @WhiteShadows no, you've turned half of your question into an answer. If you want to post an answer, do that: post an answer, and leave your question as it was, otherwise nobody can understand the question anymore. I've rollbacked to the question as it was initially. – JB Nizet Oct 01 '18 at 19:28
  • 1
    got it. Thanks for correcting – White Shadows Oct 01 '18 at 19:30
  • Just to make sure we understand correctly, do you mean that in your code you are *parsing* (not passing) String as "2018-09-15 12:00:00"? – Ole V.V. Oct 02 '18 at 03:17

3 Answers3

3

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.

Andreas
  • 154,647
  • 11
  • 152
  • 247
3

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();
}
White Shadows
  • 139
  • 1
  • 2
  • 12
  • 1
    FYI, the code would be more readable (IMHO) if you parsed first and converted after: LocalDate.parse(date, formatter).atTime(LocalTime.NOON) – JB Nizet Oct 01 '18 at 19:31
  • I believe that you don’t need to define your own formatter. The built-in `DateTimeFormatter.BASIC_ISO_DATE` can parse your input string. – Ole V.V. Oct 02 '18 at 03:19
0

Parse the date with proper mask "yyyyMMdd"

SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
Date date = format.parse("20180915");
long epochs = date.getTime();
Deian
  • 1,237
  • 15
  • 31
  • 1
    That gives `1536984000000` for me, not the `1537012800000` value requested in the question. – Andreas Oct 01 '18 at 19:31
  • 2
    You should not suggest nor endorse using obsolete classes. [`Date` is such a case](https://stackoverflow.com/questions/1969442/whats-wrong-with-java-date-time-api); use the Java Time API instead. – MC Emperor Oct 01 '18 at 20:55
  • @MCEmperor ... Last time I checked date is NOT depricated: https://docs.oracle.com/javase/7/docs/api/java/util/Date.html Unfortunately most of the enterprises are still running on J2EE7 so Date is still fair game. – Deian Oct 01 '18 at 21:04
  • 1
    @Deian I never said it was deprecated, I said it is obsolete - and it is. Many methods within the Date class are deprecated, and the docs themselves mention some cases where the Date class is insufficient. You should not teach people to use this class. – MC Emperor Oct 01 '18 at 21:45
  • 1
    Please, while I agree completely with @MCEmperor on the general level, this is especially true when the asker is already using java.time, the modern date and time API. When the question is how to use the good tool, why would you suggest using a bad tool instead? – Ole V.V. Oct 02 '18 at 03:09