以日期时间格式1980-01-01转换纪元日期

时间:2017-07-23 05:03:35

标签: java android date-format epoch

这是我的代码

private Date getReferenceDate(int seg) {

    switch (seg) {
        case 1:
        case 2:
        case 3:
            return new Date(1980-01-01);
        case 31:
        case 32:
        case 33:
            return new Date(1970-01-01);
        default:
            return new Date(1980-01-01);
    }
}

 private Date getDateFormat(int time, int seg) {
    Date date = getBaseReferenceDate(seg);
    date.setSeconds(date.getSeconds() + time);
    date.setHours(date.getHours() - 5);
    date.setMinutes(date.getMinutes() - 30);
    date.setSeconds(date.getSeconds()-1);
    return date;
}

我的日期为1185106460格式 我想把它转换成2017-07-21 12:14:20这种格式 我得到错误的输出1980-01-01

2 个答案:

答案 0 :(得分:2)

我认为以下是你想要的。

即使您使用的是Android,因此没有内置的现代Java日期和时间API,我也在使用它,因为它更方便,特别是对于这种操作。您可以在ThreeTenABP中找到它,请参阅How to use ThreeTenABP in Android Project

private static OffsetDateTime getReferenceDate(int seg) {
    int baseYear = 1970;
    if (seg >= 31 && seg <= 33) {
        baseYear = 1980; 
    }
    return OffsetDateTime.of(LocalDate.of(baseYear, Month.JANUARY, 1), 
                             LocalTime.MIDNIGHT,
                             ZoneOffset.UTC);
}

private static OffsetDateTime getDateFormat(int time, int seg) {
    return getReferenceDate(seg).plusSeconds(time);
}

看到它的工作:

    System.out.println(getDateFormat(1185106460, 1));

打印:

2007-07-22T12:14:20Z

这是您要求的日期和时间。

如果您只想要yyyy-mm-dd格式的日期:

    System.out.println(getDateFormat(1185106460, 1)
            .format(DateTimeFormatter.ISO_LOCAL_DATE));

打印

2007-07-22

如果您需要过时的Date对象,例如您无法更改的某些旧版API:

    System.out.println(DateTimeUtils.toDate(getDateFormat(1185106460, 1).toInstant()));

在我的电脑上打印:

Sun Jul 22 14:14:20 CEST 2007

这是相同的时间点,只有Date.toString()将其格式化为JVM的时区设置。在Java 8或更高版本中,转换将是

    System.out.println(Date.from(getDateFormat(1185106460, 1).toInstant()));

你做错了什么?首先,你在Date中使用了弃用的方法。这些因为某个原因而被弃用,它们在时区中不可靠,因此您不想使用它们。您可能还打算使用其中一个已弃用的Date构造函数,但您使用的是未弃用的构造函数。 1980-01-01是一个带有两个减法的算术表达式。 01是八进制整数文字,值为1,因此表达式的结果为1978.您将1978传递给构造函数Date(long date),其中它们被解释为自1970-01年以来的毫秒数-01T00:00:00Z

如果您打算将上述纪元作为参考,那么您将近距离,仅需1968毫秒。我怀疑你最后减1秒是你试图弥补这一点。如果您打算参考1980年的参考文献,那么您将享受10年的假期,节省1978毫秒。这导致了这个问题。

在任何情况下,Date都已过时,并不适合您尝试的操作。我推荐ThreeTenABP。如果你真的,真的不想依赖外部库(直到现代API来到Android),你可以查看Calendar和/或GregorianCalendar类,但它们很麻烦和errorprone,只是被警告。

答案 1 :(得分:-1)

您可以通过以下方式转换日期中的长日期:

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
String date=dateFormat.format(new Date(long timeInMillis));
相关问题