Java时间与日期处理

浅浅的花香味﹌ 2023-09-24 16:15 142阅读 0赞

返回指定格式的当前时间

  1. Date date = new Date();
  2. SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
  3. String datestring = simpleDateFormat.format(date);
  4. System.out.printf(datestring);

返回固定格式的Date类型时间Date—》ToString—》ToDate

  1. public static String TimeFormat ="yyyy-MM-dd";
  2. public static void main(String[] args) {
  3. Date date =new Date(System.currentTimeMillis());
  4. SimpleDateFormat simpleDateFormat = new SimpleDateFormat(TimeFormat);
  5. String dateformat=simpleDateFormat.format(date);
  6. System.out.printf(dateformat);
  7. Date dateafterFormat =null;
  8. try {
  9. dateafterFormat=simpleDateFormat.parse(dateformat);
  10. System.out.printf(String.valueOf(dateafterFormat));
  11. } catch (ParseException e) {
  12. throw new RuntimeException(e);
  13. }
  14. }

字符串转日期

  1. #parse(String text, ParsePosition pos)
  2. #解析字符串中的文本以Date生成,parase需要背用try-catch包围
  3. String dateTime ="2023-01-16 17:35:16";
  4. SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
  5. try {
  6. Date date =simpleDateFormat.parse(dateTime);
  7. System.out.printf(date.toString());
  8. } catch (ParseException e) {
  9. throw new RuntimeException(e);
  10. }

两时间关系判断构件

  1. #时间相等返回0,time1大于time2返回1,time1小于time2返回-1
  2. Date time1 = new Date(System.currentTimeMillis());
  3. String date ="2023-01-17 17:35:16";
  4. Date time2 = null;
  5. try {
  6. time2 = new SimpleDateFormat("yyyy-MM-dd").parse(date);
  7. } catch (ParseException e) {
  8. throw new RuntimeException(e);
  9. }
  10. int flag =time1.compareTo(time2);
  11. System.out.printf(flag+"");

Date转换为字符串

  1. public static String date2Str(Date date, String format) {
  2. if (null == date) {
  3. return null;
  4. }
  5. SimpleDateFormat sdf = new SimpleDateFormat(format);
  6. return sdf.format(date);
  7. }

发表评论

表情:
评论列表 (有 0 条评论,142人围观)

还没有评论,来说两句吧...

相关阅读