java时间戳日期格式化
在Java中,可以使用SimpleDateFormat类来将时间戳格式化为日期字符串,或将日期字符串解析为时间戳。
以下是一个示例:
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatExample {
public static void main(String[] args) {
long timeStamp = System.currentTimeMillis();
Date date = new Date(timeStamp);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = sdf.format(date);
System.out.println("Formatted date: " + formattedDate);
String dateString = "2022-01-01 12:00:00";
try {
Date parsedDate = sdf.parse(dateString);
long parsedTimeStamp = parsedDate.getTime();
System.out.println("Parsed time stamp: " + parsedTimeStamp);
} catch (Exception e) {
e.printStackTrace();
}
}
}
在此示例中,我们首先使用System.currentTimeMillis()获取当前时间戳。然后,我们将时间戳转换为Date对象,并使用SimpleDateFormat将其格式化为日期字符串。我们还演示了如何将日期字符串解析为时间戳,方法是使用SimpleDateFormat的parse()方法将日期字符串转换为Date对象,然后使用getTime()方法获取时间戳。
输出:
Formatted date: 2022-09-20 17:42:50
Parsed time stamp: 1641024000000
原文地址: http://www.cveoy.top/t/topic/bAZM 著作权归作者所有。请勿转载和采集!