gpt4 book ai didi

java - 将 03/03/2015 转换为 3/3/2015 的简单快速方法

转载 作者:行者123 更新时间:2023-12-01 07:56:48 25 4
gpt4 key购买 nike

我需要将 03/03/2015 转换为 3/3/2015。

这是我的代码:

public class getCorrectDates {

public static void main(String[] args) throws ParseException {

List<String> dates = getCorrectDates.getDates("3/2/2014", "03/03/2015");

System.out.println(dates);

}

public static List getDates(String dateStart, String dateEnd) throws ParseException {

List<Date> dates = new ArrayList<Date>();
List<String> formattedDates = new ArrayList<String>();

DateFormat formatter;

formatter = new SimpleDateFormat("MM/dd/yyyy");
Date startDate = (Date) formatter.parse(dateStart);
Date endDate = (Date) formatter.parse(dateEnd);
long interval = 24 * 1000 * 60 * 60; // 1 hour in millis
long endTime = endDate.getTime(); // create your endtime here, possibly using Calendar or Date
long curTime = startDate.getTime();
while (curTime <= endTime) {
dates.add(new Date(curTime));
curTime += interval;
}
for (int i = 0; i < dates.size(); i++) {
Date lDate = (Date) dates.get(i);
String ds = formatter.format(lDate);

formattedDates.add(ds);
System.out.println(ds);
}
return formattedDates;

}

}

输出:

02/28/201503/01/201503/02/201503/03/2015

我需要:

2/28/20153/1/20153/2/20153/3/2015

必须有一种方法可以获取数组中不带零的日期在日期和月份中。我怎样才能做到这一点?

最佳答案

满足以下条件就足够了:

new SimpleDateFormat("M/d/YYYY");

引自java docs :

Number: For formatting, the number of pattern letters is the minimum number of digits, and shorter numbers are zero-padded to this amount. For parsing, the number of pattern letters is ignored unless it's needed to separate two adjacent fields.

关于java - 将 03/03/2015 转换为 3/3/2015 的简单快速方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29062974/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com