java中日期类型与字符串相互转换

本文提供了一种使用Java进行日期和字符串互相转换的方法。通过定义日期格式,实现了从字符串到日期对象及从日期对象到字符串的转换。代码示例展示了如何进行这两种转换。
由于经常用到日期类型和字符串类型的相互转换,这里总结一下,希望能给大家有帮助。

//DateTest.java
import java.text.SimpleDateFormat;
import java.util.Date;
import java.text.ParseException;

public class DateTest{
   
   //JDK中的日期格式(年-月-日)
   public final static String jdkDateFormat = "yyyy-MM-dd";
       
   //JDK中的日期时间格式(年-月-日 时:分:秒)
   public final static String jdkDateTimeFormat = "yyyy-MM-dd HH:mm:ss";
   
   //字符串转换为日期
   public static Date strToDate(String strDate){
       SimpleDateFormat dateFormat = new SimpleDateFormat(jdkDateFormat);
       Date date = null;
       try{
      date = dateFormat.parse(strDate);
    }catch(ParseException e){
       System.out.println(e.getMessage());
    }
    return date;
   }

   //字符串转换为日期时间
public static Date strToDateTime(String strDateTime){
       SimpleDateFormat dateTimeFormat = new SimpleDateFormat(jdkDateTimeFormat);
    Date dateTime = null;
    try{
      dateTime = dateTimeFormat.parse(strDateTime);
    }catch(ParseException e){
       System.out.println(e.getMessage());
    }
    return dateTime;
   }
   
   //日期转换为字符串
   public static String dateToStr(Date date){
       SimpleDateFormat dateFormat = new SimpleDateFormat(jdkDateFormat); 
    String strDate = dateFormat.format(date);
    return strDate;
   }
   
   //日期时间转换为字符串
   public static String dateTimeToStr(Date date){
       SimpleDateFormat dateTimeFormat = new SimpleDateFormat(jdkDateTimeFormat); 
    String strDateTime = dateTimeFormat.format(date);
    return strDateTime;
   }
       
   public static void main(String[] args){
    
    //字符串转换为日期
    String strDate = new String("2007-08-19");
    String strDateTime = new String("2007-08-19 16:38:17");
    Date date = strToDate(strDate);
    Date dateTime = strToDateTime(strDateTime);

    //日期转换为字符串
    String strDate2 = dateToStr(date);
    String srtDate3 = dateToStr(dateTime);
    String strDateTime2 = dateTimeToStr(date);
    String srtDateTime3 = dateTimeToStr(dateTime);
   
    System.out.println(strDate2);
    System.out.println(srtDate3);
    System.out.println(strDateTime2);
    System.out.println(srtDateTime3);
   }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值