最近常用到日期,整理一波
JDK8
JDK8 的日期时间类:LocalDateTime LocalDate LocalTime
DateTimeFormatter TemporalAdjusters
import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
public class JDK8DateTest {
public static void main(String[] args) {
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println("localDateTime:"+localDateTime);
LocalDateTime localDateTime1 = LocalDateTime.parse("2021-01-06 10:34:14",
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
System.out.println("2021-01-06 10:34:14 parse :"+localDateTime1.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
LocalDateTime localDateTime2 = localDateTime.plusDays(1);
System.out.println("加一天 :"+localDateTime2.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
System.out.println("本月第几天 :"+ localDateTime.getDayOfMonth());
System.out.println("本月最后一天 :"+ localDateTime1.with(TemporalAdjusters.lastDayOfMonth())); // 2014-12-31
System.out.println("本月最后一个周一:"+ localDateTime1.with(TemporalAdjusters.lastInMonth(DayOfWeek.MONDAY))); // 2014-12-31
System.out.println(localDateTime1.isBefore(localDateTime1.with(TemporalAdjusters.lastInMonth(DayOfWeek.MONDAY))));
}
}
非JDK8
非jdk8 的主要用到Date, DateFormat, Calendar
DateFormat 可用于格式转换,常用的也就是String ,long ,Date型
Calendar 可用于一些计算,也提供了大量的静态类型供使用
代码:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateTest {
public static void main(String[] args) throws ParseException {
/** 1 时间格式转换*/
Date today = new Date();
// 时间转String:
String p1 = "yyyyMMdd"; // 大写MM 表示Month 小写是minute
String p3 = "yyyy-MM-dd HH:mm:ss";
String p4 = "MM";
SimpleDateFormat dateFormat = new SimpleDateFormat(p3);
String day1 = dateFormat.format(today);
System.out.println(day1);
// String 转 date
String date = "2021-01-06 10:34:14";
Date date1 = dateFormat.parse(date); // Calendar
System.out.println(dateFormat.format(date1));
System.out.println(date1);
// long型转换
Long time = date1.getTime();
System.out.println("Long-->"+time);
System.out.println(new Date(time));
/** 2 周 获取日期是周几 */
Calendar calendar = Calendar.getInstance();
calendar.setTime(date1);
System.out.println("周几--》"+(calendar.get(Calendar.DAY_OF_WEEK)-1)) ;
System.out.println("第几周--》"+(calendar.get(Calendar.WEEK_OF_YEAR)-1)) ;
System.out.println("第几月--》"+(calendar.get(Calendar.MONTH)+1)) ;
/** 3 时间计算 */
calendar.add(Calendar.MONTH,1);
System.out.println("时间计算-->"+dateFormat.format(calendar.getTime()));
calendar.add(Calendar.DATE,-7);
System.out.println("时间计算-->"+dateFormat.format(calendar.getTime()));
/** 4 是否为月最后一天 */
System.out.println("最后一天--"+ (calendar.get(Calendar.DAY_OF_MONTH) == calendar.getActualMaximum(Calendar.DAY_OF_MONTH)));
System.out.println("最后一天--"+ (calendar.get(Calendar.DAY_OF_MONTH) == 1));
}
}