Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Date string with Time to long date

Tags:

java

date

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.

like image 361
jedgard Avatar asked Jan 13 '23 01:01

jedgard


1 Answers

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.

like image 80
Jon Skeet Avatar answered Jan 15 '23 14:01

Jon Skeet