Java 从毫秒创建一个 GregorianCalendar 实例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4450238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 17:42:09  来源:igfitidea点击:

Creating a GregorianCalendar instance from milliseconds

javatimestampgregorian-calendar

提问by Amir Rachum

I have a certain time in milliseconds (in a Timestampobject) and I want to use it to create a GregorianCalendarobject. How can I do that?

我有一定的毫秒时间(在一个Timestamp对象中),我想用它来创建一个GregorianCalendar对象。我怎样才能做到这一点?

EDIT: How do I do the reverse?

编辑:我如何做相反的事情?

采纳答案by Michael Konietzka

Just get an instance of GregorianCalendar and setTime with your java.sql.Timestamp timestamp:

只需使用 java.sql.Timestamp 获取 GregorianCalendar 和 setTime 的实例timestamp

Calendar cal=GregorianCalendar.getInstance();
cal.setTime(timestamp);

Edit:As peterhpointed out, GregorianCalendar.getInstance()will not provide a GregorianCalendarby default, because it is inherited fromCalendar.getInstance(), which can provide for example a BuddhistCalendaron some installations. To be sure to use a GregorianCalenderuse new GregorianCalendar()instead.

编辑:正如peterh 所指出GregorianCalendar.getInstance()GregorianCalendar,默认情况下不会提供 a ,因为它是从 继承的Calendar.getInstance(),例如可以BuddhistCalendar在某些安装中提供 a 。一定要使用GregorianCalenderusenew GregorianCalendar()来代替。

回答by stark

I believe this works, although it may not be the best approach:

我相信这是有效的,尽管它可能不是最好的方法:

import java.sql.Date;
import java.sql.Timestamp;
import java.util.GregorianCalendar;

public class TimestampToGregorianCalendar {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Timestamp t = new Timestamp(12356342); // replace with existing timestamp
        Date d = new Date(t.getTime());
        Calendar gregorianCalendar = GregorianCalendar.getInstance();
        gregorianCalendar.setTime(d);
    }

}

回答by aepryus

Timestamp timestamp = new Timestamp(23423434);
Calendar calendar = GregorianCalendar.getInstance();
calendar.setTimeInMillis(timestamp.getTime());

回答by haaduken

To get a GregorianCalendar object and not a Calendar object. Like Michael's answer provides, you can also do the following:

获取 GregorianCalendar 对象而不是 Calendar 对象。就像迈克尔的回答所提供的那样,您还可以执行以下操作:

long timestamp = 1234567890;
GregorianCalendar cal = new GregorianCalendar();
cal.setTimeInMillis(timestamp);

This assumes a UTC epoch timestamp.

这假定 UTC 纪元时间戳。