如何在 Java 中获取给定日期和时间的毫秒数?
java.text.SimpleDateFormat 类用于格式化和解析字符串到日期以及日期到字符串。
- 该类的构造函数之一接受表示所需日期格式的字符串值,并创建SimpleDateFormat 对象。
- 要将字符串解析/转换为 Date 对象,请通过传递所需的格式字符串来实例化此类。
- 使用 parse() 方法解析日期字符串。
- 您可以使用 getTime() 方法获取纪元时间。
示例
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Sample {
public static void main(String args[]) throws ParseException {
//Instantiating the SimpleDateFormat class
SimpleDateFormat dateformatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
//Parsing the given String to Date object
String str = "25-08-2009 11:20:45";
Date date = dateformatter.parse(str);
long msec = date.getTime();
System.out.println("Epoch of the given date: "+msec);
}
}输出
Epoch of the given date: 1251179445000
您可以使用set() 方法将日期和时间值设置为日历对象。此类的 getTimeInMillis() 返回日期值的纪元时间。
示例
import java.util.Calendar;
public class Sample {
public static void main(String args[]) {
Calendar cal = Calendar.getInstance();
cal.set(2014, 9, 11, 10, 25, 30);
long msec = cal.getTimeInMillis();
System.out.print(msec);
}
}输出
1413003330758
您可以使用of() 方法将日期和时间值设置为 ZonedDateTime 对象。Instant 类的 toEpochMilli() 返回日期值的纪元时间。
示例
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Sample {
public static void main(String args[]){
//Creating the ZonedDateTime object
ZoneId id = ZoneId.of("Asia/Kolkata");
ZonedDateTime obj = ZonedDateTime.of(2014, 9, 11, 10, 25, 30, 22, id);
Instant instant = obj.toInstant();
long msec = instant.toEpochMilli();
System.out.println("Milli Seconds: "+msec);
}
}输出
Milli Seconds: 1410411330000
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP