将日期字符串与时间转换为长日期 [英] Convert Date string with Time to long date

查看:115
本文介绍了将日期字符串与时间转换为长日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,日期10:00 AM 03/29/2011,我需要使用Java将其转换为很长时间,因为我不能使用Date它不赞成,它没有给我正确的时间..所以我在网上看看如何来,但仍然没有运气。首先使用java。

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.

推荐答案

问题是你正在解析数据,然后弄乱它没有明显的原因,忽略 Date.getYear()等的记录返回值。

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.

您可能只想要这样的东西: / p>

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);
}

如果您真的想要一个 long ,只需使用:

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.)

与以前一样,我强烈建议你使用 Joda时间在Java中的日期/时间工作 - 它比java.util.Date/Calendar/etc更干净的API 。

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.

这篇关于将日期字符串与时间转换为长日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆