4

I have a string with date "10:00 AM 03/29/2011", I need to convert this to a long using Java, I cant use Date because its deprecated and it was not giving me the time correctly.. so i looked online to see how to come about it but still no luck. First time using java.

jedgard
  • 868
  • 3
  • 23
  • 41
  • 1
    `Date` isn't deprecated. Several methods within it are, but that's a different matter. You haven't said what happens with the code you've provided. – Jon Skeet Jun 25 '13 at 18:42
  • I get a value like -58587811199953, and i am trying to come up with the correct way to get the long value., then when i enter it here http://www.epochconverter.com/, it should give me the correct date, june 29 2013 8:00 AM – jedgard Jun 25 '13 at 18:55

2 Answers2

8

The problem is you're parsing the data and then messing around with it for no obvious reason, ignoring the documented return value for Date.getYear() etc.

You probably just want something like this:

private static Date parseDate(String text)
    throws ParseException
{
    SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm a MM/dd/yyyy",
                                                       Locale.US);      
    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    return dateFormat.parse(text);
}

If you really want a long, just use:

private static long parseDate(String text)
    throws ParseException
{
    SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm a MM/dd/yyyy",
                                                       Locale.US);      
    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    return dateFormat.parse(text).getTime();
}

Note that I'm punting the decision of what to do if the value can't be parsed to the caller, which makes this code more reusable. (You could always write another method to call this one and swallow the exception, if you really want.)

As ever, I'd strongly recommend that you use Joda Time for date/time work in Java - it's a much cleaner API than java.util.Date/Calendar/etc.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

java.time

The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.

Solution using java.time, the modern Date-Time API:

  1. Parse the Date-Time string into LocalDateTime.
  2. Convert the LocalDateTime to Instant.
  3. Convert Instant to the Epoch milliseconds.

Demo:

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        String strDateTime = "10:00 AM 03/29/2011";
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("h:m a M/d/u", Locale.ENGLISH);
        LocalDateTime ldt = LocalDateTime.parse(strDateTime, dtf);

        Instant instant = ldt.atZone(ZoneId.systemDefault()).toInstant();

        long epochMillis = instant.toEpochMilli();
        System.out.println(epochMillis);
    }
}

Output in my timezone, Europe/London:

1301389200000

ONLINE DEMO

Some important notes about this code:

  1. ZoneId.systemDefault() gives you to the JVM's ZoneId.
  2. If 10:00 AM 03/29/2011 belongs to some other timezone, replace ZoneId.systemDefault() with the applicable ZoneId e.g. ZoneId.of("America/New_York").
  3. If 10:00 AM 03/29/2011 is in UTC, you can do either of the following:
    • get the Instant directly as ldt.toInstant(ZoneOffset.UTC) or
    • replace ZoneId.systemDefault() with ZoneId.of("Etc/UTC") in this code.
  4. The timezone of the Ideone server (the online IDE) is UTC whereas London was at an offset of +01:00 hours on 03/29/2011 and hence the difference in the output from my laptop and the one you see in the ONLINE DEMO. Arithmetic: 1301389200000 + 60 * 60 * 1000 = 1301392800000

Learn more about the modern Date-Time API from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110