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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With