时间和日期格式的转换
在Java的实际编程当中,我们是无法直接获取到中文格式下的时间字符串的,因此我们就需要一些特定的方法将系统默认的时间字符串(类似于:Sun Jan 24 14:38:10 CST 2021)或时间戳(类似于:1611470330000)转换为定制的字符格式(类似于:yyyy年MM月dd日 HH:mm:ss格式)。
一.表示方法及常用类
(一).时间戳
在Java中可以使用System.currentTimeMillis()获取到当前时间,但是它的格式是表示从1970-01-01 00:00:00:00 开始到现在所经过的毫秒数,返回值为一个long类型的基本数据类型。类似于:1611470330000,也叫做时间戳。
(二).Date日期类
Date类中的很多方法现在都已近过时,但是我们可以使用它的getTime()方法获取到当前的日期字符串和时间戳。
import java.util.Date;
public class Test {
// 获取当前日期字符串和时间戳
public class Test {
public static void main(String[] args) {
Date date = new Date();
System.out.println(date);
// Wed Mar 17 21:37:25 CST 2021
long time = date.getTime();
System.out.println(time);
// 1615988245109
}
}
(三).Local
Local表示了特定的地理、政治和文化地区。
import java.util.Locale;
public class Test {
public static void main(String[] args) {
// 获取Java虚拟机当前的默认环境语言值
Locale locale = Locale.getDefault();
// 国家
String country = locale.getCountry();
// 语言
String language = locale.getLanguage();
System.out.println(country);//CN
System.out.println(language);//zh
}
}
(四).SimpleDateFormat
通常使用SimpleDateFormat来解析时间或日期,实现中文时间字符串与时间戳、默认时间字符串的相互转换。
常用方法
方法 | 概述 |
---|---|
public SimpleDateFormat(String pattern,Locale locale) | 有参构造函数 |
public final String format(Date date) | 将日期转为字符串 |
public Date parse(String source) | 将字符串表示转为日期 |
时间格式:
具体使用将在下面时间的相互转换中使用
二.时间定制转换
(一).当前日期字符串转换为中文时间
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class Test {
public static void main(String[] args) {
Date date = new Date();
System.out.println(date);// 当前英文时间字符串
long time = date.getTime();
System.out.println(time); // 当前时间戳
String pattern = "yyyy-MM-dd HH:mm:ss"; // 匹配格式
Locale locale = Locale.getDefault(); // 默认当前虚拟机环境
SimpleDateFormat format = new SimpleDateFormat(pattern, locale);
String string = format.format(time);
System.out.println(string);
}
}
(二).当前时间字符串转换为时间戳
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class Test {
public static void main(String[] args) throws Exception {
String timeString ="2020-03-17 21:59:59";
String pattern = "yyyy-MM-dd HH:mm:ss";
Locale locale = Locale.getDefault();
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern, locale);
Date parse = dateFormat.parse(timeString);
System.out.println(parse);// 英文时间格式
long time = parse.getTime();
System.out.println(time);// 时间戳
}
}