本文内容来自网络,很多是来自网络大佬的,我也忘记了来自哪里了,总的内容是我看别人的内容整理出来的。
Date类
import java.util.Date;
public class DateTest {
public static void main(String[] args) {
Date date = new Date();
System.out.println("现在的系统时间是:"+date);
long time=date.getTime();
System.out.println("当前时间距离UTC时间的毫秒数:"+time);
}
}
SimpleDateFormat类
public class SimpleDateFormatTest {
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH小时mm分钟ss秒S毫秒");
System.out.println("使用指定格式的日期字符串:"+sdf.format(new Date()));
String str="2021年1月15日 06小时44分钟05秒 123毫秒";
Date date = sdf.parse(str);
System.out.println("日期对象:"+date);
}
}
LocalDate、LocalTime、LocalDateTime类
import java.time.LocalDateTime;
public class LocalDateTimeTest {
public static void main(String[] args) {
//1、创建一个日期对象
LocalDateTime now = LocalDateTime.now();
//2、获取日历字段
System.out.println("年:"+now.getYear());
System.out.println("月:"+now.getMonthValue());
System.out.println("月:"+now.getMonth());
System.out.println("日:"+now.getDayOfMonth());
System.out.println("小时:"+now.getHour());
System.out.println("分钟:"+now.getMinute());
System.out.println("秒:"+now.getSecond());
}
}
@Test
public void LocalDateTime()
{
LocalDateTime now=LocalDateTime.now();
System.out.println(now);
LocalDateTime now2 = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDateTime = now2.format(formatter);
System.out.println(formattedDateTime);
}
DateTimeFormatter类
java.time.format.DateTimeFormatter类提供了格式化日期的方法,这个类和第一代日期的SimpleDateFormatter类似,但SimpleDateFormat只能格式化Date类,对Calendar类无效。DateTimeFormatter可以格式化LocalDate、LocalTime、LocalDateTime及Instant类。
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class DateTimeFormatterTest {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd a hh小时mm分钟ss秒");
//格式化日期(日期->文本)
String format = dtf.format(now);
System.out.println(format);
//解析字符串为日期(文本->日期)
String s="2018-08-08 下午 05小时06分钟43秒";
LocalDateTime parse = LocalDateTime.parse(s, dtf);
System.out.println(parse);
}
}
2、获取当前时间
下面的代码用的是java中的测试模块,如果要测试,可以直接复制单个@Test下面的 {}里面的代码进行测试查看
@Test
public void Date()
{
Date date=new Date();
System.out.println(date.toString());
System.out.println(date);
}
@Test
public void SimepleDateFormat()
{
Date dnow=new Date();
SimpleDateFormat ft=new SimpleDateFormat("yyyy-MM-dd ::E");
System.out.println(ft.format(dnow));
System.out.println(ft.format(dnow).getClass());
}
@Test
public void LocalDateTime()
{
LocalDateTime now=LocalDateTime.now();
System.out.println(now);
LocalDateTime now2 = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDateTime = now2.format(formatter);
System.out.println(formattedDateTime);
}
String nowTime = DateTimeFormatter.ofPattern("yyyy-MM-dd").format(LocalDateTime.now());