JAVA 总结一些常用的时间函数
1. Date 转 String
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = sdf.format(new Date());
2. String 转 Date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = sdf.parse("2020-03-27 09:27:21");
3. String 转 Timestamp
Timestamp timestamp= Timestamp.valueOf("2020-03-27 12:09:12");
4. Timestamp 转 String
Timestamp time = new Timestamp(System.currentTimeMillis());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String strTime = sdf.format(time);
5. 获取当前时间的前一天/后一天
Calendar calendar = Calendar.getInstance();//当前时间
calendar.add(Calendar.DATE, -1); //得到前一天
Date date = calendar.getTime();
Calendar calendar = Calendar.getInstance();//当前时间
calendar.add(Calendar.DATE, 1);//得到后一天
Date date = calendar.getTime();
注:年 或 小时 也同理,将DATE换成YEAR / HOUR
6. 获取月份中第一天和最后一天
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String time = "2022-05";
//本月第一天
Date startTime = sdf.parse(time+"-01");
Calendar calendar = Calendar.getInstance();
calendar.setTime(startTime);
calendar.add(Calendar.MONTH,1);//月增加1天
calendar.add(Calendar.DAY_OF_MONTH,-1);//日期倒数一日,既得到本月最后一天
//本月最后一天
Date endTime = calendar.getTime();
7. 获取两个日期中所有月份
Calendar min = Calendar.getInstance();//开始时间
Calendar max = Calendar.getInstance();//结束时间
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");//格式化为年月
min.setTime(sdf.parse("2019-10"));//为开始时间赋值
min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);
max.setTime(sdf.parse("2020-03"));//为结束时间赋值
max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);
Calendar curr = min;
ArrayList<String> result = new ArrayList<String>();
while (curr.before(max)) {
result.add(sdf.format(curr.getTime()));
curr.add(Calendar.MONTH, 1);//月份往后加一个月
}
8. 获取指定年月的月份天数
实例1: 2020年02月
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");//指定转换格式
LocalDate date = LocalDate.parse("2020-02-01", fmt);//进行转换
int month = date.lengthOfMonth();//该月份有多少天
注意:这里的日期一定要年月日的格式 如果只有年月可以随意拼接一个天
实例2: 2020年02月
Calendar a = Calendar.getInstance();
a.set(Calendar.YEAR, 2020);//赋值年份
//Calendar中的Month是从0-11的,0代表1月,11代表12月
a.set(Calendar.MONTH, 02 - 1);//赋值月份
a.set(Calendar.DATE, 1);//赋值天份
a.roll(Calendar.DATE, -1);
int maxDate = a.get(Calendar.DATE);
9. 根据指定日期获取对应星期机
SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
Date myDate = myFormatter.parse("2020-03-27");
SimpleDateFormat formatter = new SimpleDateFormat("E");//星期格式
String str = formatter.format(myDate);
str : 星期五
SimpleDateFormat函数语法:
G 年代标志符
y 年
M 月
d 日
h 时 在上午或下午 (1~12)
H 时 在一天中 (0~23)
m 分
s 秒
S 毫秒
E 星期
D 一年中的第几天
F 一月中第几个星期几
w 一年中第几个星期
W 一月中第几个星期
a 上午 / 下午 标记符
k 时 在一天中 (1~24)
K 时 在上午或下午 (0~11)
z 时区