【问题标题】:convert date into different format将日期转换为不同的格式
【发布时间】:2016-04-07 12:21:08
【问题描述】:

我正在尝试将日期转换为用户所需的格式。我想要所有格式的日期。 但是格式的日期是错误的,请帮忙。

package DateFormat;

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

public class DateFormat
{
    DateFormat() throws ParseException
    {
    String dateFormats[] =
    {
            "YYYY/MM/DD",
            "DD/MM/YYYY",
            "DD-MM-YYYY",
    };


    for (int i = 0; i < dateFormats.length; i++)
    {

        String newDate = new SimpleDateFormat(dateFormats[i]).format(new Date());
        System.out.println(newDate);
    }

    }

    public static void main(String[] args) throws ParseException
    {
    new DateFormat();
    }
}

输出是

2016/04/98
98/04/2016
98-04-2016

谢谢。

【问题讨论】:

  • 因为,使用了错误的格式。请参阅documentation 了解支持的格式。

标签: java date date-format date-formatting


【解决方案1】:

由于 java 代码语法区分大小写而出错。 请在https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html 检查正确的日期和时间模式

您的模式字符串数组应转换为:

String dateFormats[] =
{
        "yyyy/MM/dd",
        "dd/MM/yyyy",
        "dd-MM-yyyy",
};

【讨论】:

    【解决方案2】:
    D   Day in year Number  189
    d   Day in month    Number  10
    

    来自https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

    所以,格式应该是这样的:

    String dateFormats[] =
    {
            "yyyy/MM/dd",
            "dd/MM/yyyy",
            "dd-MM-yyyy",
    };
    

    【讨论】:

    • YYYY 也应该是小写的,yyyy
    猜你喜欢
    • 2013-06-21
    • 1970-01-01
    • 2016-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多