将日期字符串转换为 Java 中的 Epoch
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36772489/
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
Convert Date String into Epoch in Java
提问by Ashley
Is there a way to convert a given Date
String into Milliseconds
(Epoch
Long format) in java? Example : I want to convert
有没有办法在java中将给定的Date
字符串转换为Milliseconds
(Epoch
长格式)?示例:我想转换
public static final String date = "04/28/2016";
into milliseconds (epoch).
成毫秒(纪元)。
回答by Albert
You can create a Calendar
object and then set it's date to the date you want and then call its getTimeInMillis()
method.
您可以创建一个Calendar
对象,然后将其日期设置为您想要的日期,然后调用其getTimeInMillis()
方法。
Calendar c = new Calendar.getInstance();
c.set(2016, 3, 28);
c.getTimeInMillis();
If you want to convert the String
directly into the date you can try this:
如果你想String
直接转换成日期,你可以试试这个:
String date = "4/28/2016";
String[] dateSplit = date.split("/");
c.set(Integer.valueOf(dateSplit[2]), Integer.valueOf(dateSplit[0]) - 1, Integer.valueOf(dateSplit[1]));
c.getTimeInMillis();
回答by Paul Ostrowski
The getTime() method of the Date class returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.
Date 类的 getTime() 方法返回自 1970 年 1 月 1 日格林威治标准时间 00:00:00 以来由该 Date 对象表示的毫秒数。
回答by Davy Jones
You will need to use Calendar instance for getting millisecond from epoch
您将需要使用 Calendar 实例从纪元获取毫秒
try {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
java.util.Date d = sdf.parse("04/28/2016");
/*
* Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.
*/
System.out.println(d.getTime());
//OR
Calendar cal = Calendar.getInstance();
cal.set(2016, 3, 28);
//the current time as UTC milliseconds from the epoch.
System.out.println(cal.getTimeInMillis());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
回答by aichy
You can simply parse it to java.util.Date using java.text.SimpleDateFormat and call it's getTime() function. It will return the number of milliseconds since Jan 01 1970.
您可以简单地使用 java.text.SimpleDateFormat 将其解析为 java.util.Date 并调用它的 getTime() 函数。它将返回自 1970 年 1 月 1 日以来的毫秒数。
public static final String strDate = "04/28/2016";
try {
Long millis = new SimpleDateFormat("MM/dd/yyyy").parse(strDate).getTime();
} catch (ParseException e) {
e.printStackTrace();
}