java的时间相关的api
JDK1.8之前
public class SimpleDateFormat
extends DateFormat
SimpleDateFormat是一个具体的类,用于以区域设置敏感的方式格式化和解析日期。 它允许格式化(日期文本),解析(文本日期)和归一化。
Date和SimpleDateFormat之间的转换
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");//.getInstance("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
System.out.println(sdf.format(date);
System.out.println(sdf.format(System.currentTimeMillis()));
java.util.date 和 java.sql.Date 转换
将字符串”2020-09-08“ 转换成mysql 中的date 例如”2020-09-08“
String birth = "2020-09-08";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");// 格式化
Date date = sdf.parse(birth);// 解析
java.sql.Date birthDate = new java.sql.Date(date.getTime());
System.out.println(birthDate);// 这里 直接打印是因为系统已经帮我们重写了toSting
Calendar 类
Calendar calendar = Calendar.getInstance();
calendar.get(Calendar.DAY_OF_MONTH);
calendar.get(Calendar.DAY_OF_WEEK);// 周日是第一天
calendar.get(Calendar.DAY_OF_YEAR);
calendar.get(Calendar.HOUR_OF_DAY);
calendar.get(Calendar.MONTH +1);// 月份要加一
JDK1.8
LocalDateTime和DateTimeFormatter
LocalDateTime ldt = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
String str4 = formatter.format(ldt);
System.out.println(str4);
TemporalAccessor tem = formatter.parse("2020-03-16 12:08:33");
System.out.println(tem);
LocalDateTime相关API方法
public final class LocalDateTime
extends Object
implements Temporal, TemporalAdjuster, ChronoLocalDateTime<LocalDate>, Serializable
在ISO- 2007-12-03T10:15:30 ,如2007-12-03T10:15:30 。
LocalDateTime是一个不可变的日期时间对象,代表日期时间,通常被视为年 - 月 - 日 - 时 - 分 - 秒。 也可以访问其他日期和时间字段,例如日期,星期几和星期。 时间表示为纳秒精度。 例如,值“2007年10月2日在13:45.30.123456789”可以存储在LocalDateTime 。
该类不存储或表示时区。 相反,它是对日子的描述,如用于生日,结合当地时间在挂钟上看到的。 它不能代表时间线上的即时信息,而没有附加信息,如偏移或时区。
ISO-8601日历系统是当今世界绝大多数的现代民用日历系统。 它相当于今天的闰年规则一直适用于日常生活的公历日历系统。 对于今天写的大多数应用,ISO-8601规则是完全合适的。 然而,任何利用历史日期并要求它们准确的应用程序都将发现ISO-8601方法不合适。
这是一个value-based类; 使用身份敏感的操作(包括引用相等(的==上的实例),标识哈希码,或同步) LocalDateTime可具有不可预测的结果,应当避免。 equals方法应用于比较。
static LocalDateTime now()
从默认时区的系统时钟获取当前的日期时间。
static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute, int second)
从年,月,日,小时,分钟和秒获得 LocalDateTime的实例,将纳秒设置为零。
static LocalDateTime parse(CharSequence text)
从一个文本字符串(如 2007-12-03T10:15:30获取一个 LocalDateTime的实例。
LocalDateTime plusDays(long days)
返回此 LocalDateTime的副本,并以指定的时间段添加天数。
LocalDateTime minusYears(long years)
返回此 LocalDateTime的副本,并以减去的年份为单位。
DateTimeFormatter
public final class DateTimeFormatter
extends Object
格式化器用于打印和解析日期时间对象。
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy MM dd");
String text = date.toString(formatter);
LocalDate date = LocalDate.parse(text, formatter);
static DateTimeFormatter ofPattern(String pattern)
使用指定的模式创建格式化程序。
TemporalAccessor parse(CharSequence text)
完全解析产生时间对象的文本。