有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何从历元将年-月-日转换为适当的UTC毫秒?

我正在尝试使用以下代码将日期转换为毫秒:

    GregorianCalendar gc = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
    gc.clear();
    gc.set(1900, 1, 1);

    long left = gc.getTimeInMillis();

我得到left=-2206310400000,但是当我检查here时,我应该得到-2208988800000

我做错了什么


共 (2) 个答案

  1. # 1 楼答案

    爪哇。时间

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

    此外,以下引述的是home page of Joda-Time的通知:

    Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.

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

    import java.time.OffsetDateTime;
    import java.time.ZoneOffset;
    
    public class Main {
        public static void main(String[] args) {
            long epochMillis = OffsetDateTime.of(1900, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC)
                                .toInstant()
                                .toEpochMilli();
    
            System.out.println(epochMillis);
        }
    }
    

    输出:

    -2208988800000
    

    ONLINE DEMO

    Trail: Date Time了解有关现代日期时间API的更多信息


    *无论出于何种原因,如果您必须坚持使用Java 6或Java 7,您都可以使用ThreeTen-Backport作为大多数Java的后台端口。Java 6&;的时间功能;7.如果您正在为Android项目工作,并且您的Android API级别仍然不符合Java-8,请选中Java 8+ APIs available through desugaringHow to use ThreeTenABP in Android Project

  2. # 2 楼答案

    你用1表示月份,也就是二月

    你是说

    gc.set(1900, 0, 1);
    

    the docs

    month - the value used to set the MONTH calendar field. Month value is 0-based. e.g., 0 for January.

    是的,Java日期/时间API已损坏。如果您在日期/时间方面做了大量工作,我建议您使用Joda Time

    long left = new DateTime(1900, 1, 1, 0, 0, DateTimeZone.UTC).getMillis();