简体   繁体   English

将日期字符串与时间转换为长日期

[英]Convert Date string with Time to long 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. 我有一个日期为"10:00 AM 03/29/2011"的字符串,我需要使用Java将其转换为long,我不能使用Date因为它已弃用并且它没有给我正确的时间..所以我看了在线看看如何实现但仍然没有运气。 First time using java. 第一次使用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. 问题是你正在解析数据,然后没有明显的原因弄乱它,忽略了Date.getYear()等记录的返回值。

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: 如果你真的想要long ,只需使用:

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. 与以往一样,我强烈建议您使用Joda Time在Java中进行日期/时间工作 - 它比java.util.Date/Calendar/etc更清晰。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM