Java中存在的时间转换问题

(1)获取当前时间,返回时间格式为:yyyy-MM-dd HH:mm:ss
public static Date getNowDate() {
   Date currentTime = new Date();
   SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
   String dateString = formatter.format(currentTime);
   ParsePosition pos = new ParsePosition(8);
   Date currentTime_2 = formatter.parse(dateString, pos);
   return currentTime_2;
}

(2)字符串转换为指定的时间格式,返回格式为:yyyy-MM-dd或者是yyyy年MM月dd日 HH时mm分ss秒间的相互转换

public static Date getStringToDate() {
   DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");         
   DateFormat format 2= new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");         
   Date date = null;    
   String str = null; 
   str = "2020-4-3";          
    try {    
           /*date = format1.parse(str);*/ //"yyyy-MM-dd"
           data = format2.parse(str); //"yyyy年MM月dd日 HH时mm分ss秒"
    } catch (ParseException e) {    
           e.printStackTrace();    
    }
   return date;   
}

(3)当前时间转换为指定格式的字符串,如格式:yyyy-MM-dd HH:mm:ss或者yyyy-MM-dd或者HH:mm:ss

public static String getDateToString() {
   Date currentTime = new Date();
   SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
   String dateString = formatter.format(currentTime);
   return dateString;
}

(4)得到现在的时间、现在时间的小时、分钟、秒

public static String getStringTime() {
   Date currentTime = new Date();
   SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd HHmmss");
   String dateString = formatter.format(currentTime);
   //String hour = dateString.subString(11,13);
   //String min = dateString.subString(14,16);
   return dateString;
}

(5)判断一个日期(字符串类型)是否为闰年,闰年的判断方式:

      ①.被400整除是闰年,否则: ②.不能被4整除则不是闰年 ③.能被4整除同时不能被100整除则是闰年,能被4整除同时能被100整除则不是闰年

public static boolean isLeapYear(String date) {
  Date d = strToDate(ddate);
  GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
  gc.setTime(d);
  int year = gc.get(Calendar.YEAR);
  if ((year % 400) == 0)
       return true;
  else if ((year % 4) == 0) {
       if ((year % 100) == 0)
            return false;
       else
            return true;
  } else
       return false;
 }

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值