Date与String的相互转换

Java时间转化类型

SimpleDateFormate的几种形式

 public static void main(String[] args) {
        SimpleDateFormat simpleDateFormat0 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd a E");
        SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a E");
        Date date = new Date() ;
        System.out.println(simpleDateFormat0.format(date));
        System.out.println(simpleDateFormat1.format(date));
        System.out.println(simpleDateFormat2.format(date));
    }

输出结果

2018-12-29
2018-12-29 上午 星期六
2018-12-29 11:08:53 上午 星期六

Date转换String类型

常用的转换方法:format方法

//	第一种参数为Date类型
Date date = new Date();
String date0 = simpleDateFormat0.format(date);
System.out.println(date0);
//第二种参数位Object类型
Date date = new Date();
Map<String, Object> map = new HashMap<String, Object>();
map.put("date", date);
String date1 = simpleDateFormat0.format(map.get("date"));
System.out.println(date1);

还有一种返回类型是StringBuffer的方法,感兴趣可以看一下jdk

String类型转换Date

常用的方法:simpleDateFormat的parse方法

Map<String, String> map = new HashMap<String, String>();
        map.put("date", "2018-12-29");
        Date date1 = null;
        try {
           date1 = simpleDateFormat0.parse(map.get("date"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        System.out.println(date1);

输出结果:

Sat Dec 29 00:00:00 CST 2018
Java中,DateString之间的转换是非常常见的操作,因为不同的应用程序或组件使用的日期格式可能是不同的。因此,开发者需要使用工具类来处理它们之间的转换。 下面是一个可用于DateString相互转换Java工具类: public class DateUtil { // 将日期转换为字符串 public static String dateToString(Date date, String format) { SimpleDateFormat dateFormat = new SimpleDateFormat(format); return dateFormat.format(date); } // 将字符串转换为日期 public static Date stringToDate(String str, String format) throws ParseException { SimpleDateFormat dateFormat = new SimpleDateFormat(format); return dateFormat.parse(str); } } 在上面的代码中,dateToString方法用于将日期对象转换为字符串,并传入一个特定的日期格式。stringToDate方法用于将字符串转换为日期对象,并同样需要传入日期格式。它们都使用Java中的SimpleDateFormat类来实现这些转换。 使用这个工具类,可以很方便地将日期对象转换为不同的字符串格式,或将不同格式的字符串转换为日期对象。例如: Date now = new Date(); String nowStr = DateUtil.dateToString(now, "yyyy-MM-dd HH:mm:ss"); System.out.println(nowStr); // 将输出当前时间的字符串表示,格式为"yyyy-MM-dd HH:mm:ss" String str = "2021-01-01 00:00:00"; Date newYear = DateUtil.stringToDate(str, "yyyy-MM-dd HH:mm:ss"); System.out.println(newYear); // 将输出日期对象表示"2021-01-01 00:00:00"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值