SimpleDateFormat类概述
SimpleDateFormat可以对Date对象,进行格式化和解析。
格式化
package com.shengda.Demo11Date;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateDemo3 {
public static void main(String[] args) {
// 当前时间的Date对象
Date date = new Date();
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
String result1 = sdf.format(date);
System.out.println(result1);
}
}
解析
package com.shengda.Demo11Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateDemo4 {
public static void main(String[] args) throws ParseException {
String s = "2048-01-01";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse(s);
System.out.println(date);
}
}
JDK8版本之后的对日期添加修改的操作
package com.shengda.Demo11Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
public class DateDemo5 {
public static void main(String[] args) throws ParseException {
JDKMethod(); // 8版本之后
// JDK8版本之后
String s = "2020年11月11日 00:00:00";
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");
LocalDateTime localDateTime = LocalDateTime.parse(s, pattern);
LocalDateTime newLocalDateTime = localDateTime.minusDays(1); // 减少一天
// LocalDateTime newLocalDateTime = localDateTime.plusDays(1); // 表示增加一天
String result = newLocalDateTime.format(pattern);
System.out.println(result);
}
private static void JDKMethod() throws ParseException {
String s = "2020年11月11日 00:00:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
Date date = sdf.parse(s);
long time = date.getTime();
time = time+(1000*60*60*24);
Date newDate = new Date(time);
String result = sdf.format(newDate);
System.out.println(result);
}
}
将时间修改到指定的日期
package com.shengda.Demo12DateJDK8;
import java.time.LocalDateTime;
public class JDK8DateDemo6 {
public static void main(String[] args) {
LocalDateTime localDateTime = LocalDateTime.of(2020, 12, 12, 12, 12, 12);
// LocalDateTime newLocalDateTime = localDateTime.withYear(2044); // 修改到指定的年份
LocalDateTime newLocalDateTime = localDateTime.withMonth(11); // 修改到指定的月份
System.out.println(newLocalDateTime);
}
}