将日期字符串转换为不同的格式 [英] Converting date-string to a different format

查看:193
本文介绍了将日期字符串转换为不同的格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,其格式为 YYYY-MM-DD

I have a string containing a date in the format YYYY-MM-DD.

建议我以最好的方式将其转换为格式 DD-MM-YYYY

How would you suggest I go about converting it to the format DD-MM-YYYY in the best possible way?

这是我会如何做天真的:

This is how I would do it naively:

import java.util.*;
public class test {
    public static void main(String[] args) {
         String date = (String) args[0]; 
         System.out.println(date); //outputs: YYYY-MM-DD
         System.out.println(doConvert(date)); //outputs: DD-MM-YYYY
    }

    public static String doConvert(String d) {
         String dateRev = "";
         String[] dateArr = d.split("-");
         for(int i=dateArr.length-1 ; i>=0  ; i--) {
             if(i!=dateArr.length-1)
                dateRev += "-";
             dateRev += dateArr[i];
         }
    return dateRev;
    }
}

但还有其他更优雅和有效的方式做的吗也就是使用一些内置功能?我不能找到一个,而快速搜索API。

But are there any other, more elegant AND effective way of doing it? Ie. using some built-in feature? I have not been able to find one, while quickly searching the API.

这里有人知道另一种方法吗?

Anyone here know an alternative way?

推荐答案

使用 java.util.DateFormat

DateFormat fromFormat = new SimpleDateFormat("yyyy-MM-dd");
fromFormat.setLenient(false);
DateFormat toFormat = new SimpleDateFormat("dd-MM-yyyy");
toFormat.setLenient(false);
String dateStr = "2011-07-09";
Date date = fromFormat.parse(dateStr);
System.out.println(toFormat.format(date));

这篇关于将日期字符串转换为不同的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆