Java –如何更改字符串中的日期格式

如果是Java 8,则使用DateTimeFormatter ,否则使用SimpleDateFormat更改字符串中的日期格式。

1. DateTimeFormatter(Java 8)

将字符串转换为LocalDateTime并使用DateTimeFormatter更改日期格式

DateFormatExample1.java
package com.mkyong;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class DateFormatExample1 {

	// date format 1
    private static final DateTimeFormatter dateFormatter 
		= DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S");
	
	// date format 2
    private static final DateTimeFormatter dateFormatterNew 
		= DateTimeFormatter.ofPattern("EEEE, MMM d, yyyy HH:mm:ss a");

    public static void main(String[] args) {

        String date = "2019-05-23 00:00:00.0";

		// string to LocalDateTime
        LocalDateTime ldateTime = LocalDateTime.parse(date, dateFormatter);

        System.out.println(dateFormatter.format(ldateTime));

        // change date format
        System.out.println(dateFormatterNew.format(ldateTime));


    }

}

输出量

2019-05-23 00:00:00.0

Thursday, May 23, 2019 00:00:00 AM

注意
更多Java 8 String to LocalDateTime示例

2. SimpleDateFormat

将String转换为Date并使用SimpleDateFormat更改日期格式

SimpleDateFormatExample.java
package com.mkyong;

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

public class SimpleDateFormatExample {

    private static final SimpleDateFormat sdf = 
			new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");

    private static final SimpleDateFormat sdfNew = 
			new SimpleDateFormat("EEEE, MMM d, yyyy HH:mm:ss a");

    public static void main(String[] args) {

        String dateString = "2019-05-23 00:00:00.0";

        try {

			// string to date
            Date date = sdf.parse(dateString);

            System.out.println(sdf.format(date));
			
            System.out.println(sdfNew.format(date));

        } catch (ParseException e) {
            e.printStackTrace();
        }

    }

}

输出量

2019-05-23 00:00:00.0

Thursday, May 23, 2019 00:00:00 AM

注意
更多Java String to Date示例

参考文献

翻译自: https://mkyong.com/java/java-how-to-change-date-format-in-a-string/

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值