第一代日期类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| package Learn;
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date;
public class Test { public static void main(String[] args) throws ParseException { Date date=new Date(); System.out.println(date); SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss E"); String format=simpleDateFormat.format(date); System.out.println(format);
String s="2022年03月02日 05:10:37 周三"; Date parse =simpleDateFormat.parse(s); System.out.println(parse); } }
|
第二代日期类
Calendar日历类,是一种抽象类,构造器私有化,通过getInstance得到实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| package Learn;
import java.text.ParseException; import java.util.Calendar;
public class Test { public static void main(String[] args) throws ParseException { Calendar calendar =Calendar.getInstance(); System.out.println(calendar.get(Calendar.YEAR)); System.out.println(calendar.get(Calendar.MONTH)+1); System.out.println(calendar.get(Calendar.DAY_OF_MONTH)); System.out.println(calendar.get(Calendar.HOUR_OF_DAY));
} }
|
第三代日期类
jdk8之后存在
- LocalDate(只有年月日)
- LocalTime(只有时间)
- LocalDateTime(日期+时间)
- DateTimeFormat格式化日期类
- Instant 时间戳
- 除了上述之外还增加了是否闰年,增加时间等等方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| package Learn; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.util.Date;
public class Test { public static void main(String[] args) { System.out.println(LocalDate.now()); System.out.println(LocalTime.now()); System.out.println(LocalDateTime.now()); System.out.println(LocalDateTime.now().getMonth()); System.out.println(LocalDateTime.now().getMonthValue()); DateTimeFormatter dateTimeFormatter=DateTimeFormatter.ofPattern("yyyy年MM月dd日 hh:mm:ss"); System.out.println(dateTimeFormatter.format(LocalDateTime.now())); Instant instant=Instant.now(); System.out.println(instant); Date date=Date.from(instant); System.out.println(date); instant =date.toInstant(); } }
|