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

时间:2013-06-25 18:39:25

标签: java date

我有一个日期为"10:00 AM 03/29/2011"的字符串,我需要使用Java将其转换为long,我不能使用Date因为它已被弃用而且它没有给我正确的时间..所以我在网上看到了如何实现但仍然没有运气。第一次使用java。

2 个答案:

答案 0 :(得分:8)

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

你可能只想要这样的东西:

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,请使用:

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

请注意,如果无法将值解析为调用者,我将决定该怎么做,这使得此代码更具可重用性。 (如果你真的想要,你总是可以编写另一种方法来调用这个方法并吞下异常。)

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

答案 1 :(得分:1)

java.time

java.util 日期时间 API 及其格式化 API SimpleDateFormat 已过时且容易出错。建议完全停止使用它们并切换到 modern Date-Time API*

使用 java.time(现代日期时间 API)的解决方案:

  1. 将日期时间字符串解析为 LocalDateTime
  2. LocalDateTime 转换为 Instant
  3. Instant 转换为 Epoch 毫秒。

演示:

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

在我的时区输出,欧洲/伦敦:

1301389200000

ONLINE DEMO

关于此代码的一些重要说明:

  1. ZoneId.systemDefault() 为您提供 JVM 的 ZoneId
  2. 如果 10:00 AM 03/29/2011 属于其他时区,请将 ZoneId.systemDefault() 替换为适用的 ZoneId,例如ZoneId.of("America/New_York")
  3. 如果 2011 年 3 月 29 日上午 10:00 是 UTC,您可以执行以下任一操作:
    • 直接获取 Instant 作为 ldt.toInstant(ZoneOffset.UTC)
    • 将此代码中的 ZoneId.systemDefault() 替换为 ZoneId.of("Etc/UTC")
  4. Ideone 服务器(在线 IDE)的时区是 UTC 而 London was at an offset of +01:00 hours on 03/29/2011,因此我的笔记本电脑的输出与您在在线演示中看到的输出不同。 算术: 1301389200000 + 60 * 60 * 1000 = 1301392800000

Trail: Date Time 了解有关现代 Date-Time API 的更多信息。


* 出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用 ThreeTen-Backport,它将大部分 java.time 功能向后移植到 Java 6 & 7. 如果您正在为 Android 项目工作并且您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaringHow to use ThreeTenABP in Android Project