java:simpledateformat不简化为指定的模式?

0ve6wy6x  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(299)

这个问题在这里已经有答案了

以特定格式显示java.util.date(10个答案)
希望当前日期和时间为“dd/mm/yyyy hh:mm:ss.ss”格式(10个答案)
将java.util.date转换为java.util.date,并在java中使用不同的格式[重复](1个答案)
SimpleDataFormat解析时忽略月份(4个答案)
上个月关门了。
尝试使用simpledateformat.parse(“yyyy-mm-dd”)将yyyy-mm-dd字符串(例如2013-12-30)转换为日期对象。
2013年12月30日预计产量,2013年12月30日周一00:00:00东部标准时间收到产量。
尝试找出SimpleDataFormat返回不同格式的原因,但在尝试查看JavaAPI时不知所措。要求澄清正在发生的事情以及什么是更好的办法。
注意:使用java.utl.date时卡住了。

...
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

    dateArray = new Date[rowCount];

    try {
        for(int index = 0; index < rowCount; index++){
            dateArray[index] = simpleDateFormat.parse(fileArray[index][0]);
            System.out.println(dateArray[index].toString());
        }
    } catch(ParseException err){
        System.out.println("ERR: Data parse exception. Format is not correct.");
        err.printStackTrace();
    }
2g32fytz

2g32fytz1#

模式, mm 代表分钟,不是月。一个月,你需要使用 MM .
演示:

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

public class Main {
    public static void main(String[] args) throws ParseException {
        String strDate = "2013-12-30";
        SimpleDateFormat sdfISO8601 = new SimpleDateFormat("yyyy-MM-dd");
        Date date = sdfISO8601.parse(strDate);
        System.out.println(date);

        String strDateISO8601 = sdfISO8601.format(date);
        System.out.println(strDateISO8601);

        // Some other format
        String strSomeOtherFormat = new SimpleDateFormat("EEEE MMM dd yyyy").format(date);
        System.out.println(strSomeOtherFormat);
    }
}

我还建议您选中将utc字符串转换为utc日期。
注意,api的日期时间 java.util 以及它们的格式化api, SimpleDateFormat 过时且容易出错。我建议您完全停止使用它们,转而使用现代的日期时间api。
使用现代日期时间api:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        String strDate = "2013-12-30";
        LocalDate date = LocalDate.parse(strDate);
        System.out.println(date);

        String strDate8601 = date.toString();
        System.out.println(strDate8601);

        // Custom format
        String customFormat = DateTimeFormatter.ofPattern("EEEE MMM dd uuuu").format(date);
        System.out.println(customFormat);
    }
}

您的日期字符串已经是iso8601格式的日期,因此在使用现代日期时间api时不需要使用任何格式化程序来解析它。
在trail:date-time了解有关现代日期时间api的更多信息。
如果您正在为一个android项目工作,并且您的android api级别仍然不符合java-8,请检查通过desugaring提供的java8+api以及如何在android项目中使用threetenabp。

相关问题