目录
1.返回指定格式的当前时间,Date-->FormatString,Date类型转Strig
2.返回固定格式的Date类型时间Date---》ToString---》ToDate,Date类型格式化成Date
3.字符串转日期 String格式化成String
4.两时间关系判断构件
5.Date转换为字符串:Date格式化成String
6.String类型时间戳格式化成日期格式String
1.返回指定格式的当前时间,Date-->FormatString,Date类型转Strig
Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String datestring = simpleDateFormat.format(date);
System.out.printf(datestring);
2.返回固定格式的Date类型时间Date---》ToString---》ToDate,Date类型格式化成Date
public static String TimeFormat ="yyyy-MM-dd";
public static void main(String[] args) {
Date date =new Date(System.currentTimeMillis());
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(TimeFormat);
String dateformat=simpleDateFormat.format(date);
System.out.printf(dateformat);
Date dateafterFormat =null;
try {
dateafterFormat=simpleDateFormat.parse(dateformat);
System.out.printf(String.valueOf(dateafterFormat));
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
3.字符串转日期 String格式化成String
#parse(String text, ParsePosition pos)
#解析字符串中的文本以Date生成,parase需要背用try-catch包围
String dateTime ="2023-01-16 17:35:16";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date =simpleDateFormat.parse(dateTime);
System.out.printf(date.toString());
} catch (ParseException e) {
throw new RuntimeException(e);
}
4.两时间关系判断构件
#时间相等返回0,time1大于time2返回1,time1小于time2返回-1
Date time1 = new Date(System.currentTimeMillis());
String date ="2023-01-17 17:35:16";
Date time2 = null;
try {
time2 = new SimpleDateFormat("yyyy-MM-dd").parse(date);
} catch (ParseException e) {
throw new RuntimeException(e);
}
int flag =time1.compareTo(time2);
System.out.printf(flag+"");
5.Date转换为字符串:Date格式化成String
public static String date2Str(Date date, String format) {
if (null == date) {
return null;
}
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(date);
}
6.String类型时间戳格式化成日期格式String
public static String changesStringTimestamToformat(String timestamp){
LocalDateTime parse = LocalDateTime.ofInstant(Instant.ofEpochMilli(Long.parseLong(timestamp)), ZoneId.systemDefault());
String format = parse.format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss"));
return format;
}