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

标签 java date converters

我需要将 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/2015

03/01/2015

03/02/2015

03/03/2015

我需要:

2/28/2015

3/1/2015

3/2/2015

3/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/

相关文章:

c - 在 C 中将字符串转换为 morze 时 Printf() 不起作用

jsf - 如果 f :viewParam/converter returns null?,如何将某人发送到 404 页面

java - 通过 UDP 发送数据时是否应该使用相同的端口号?

java - STS,运行任何指南项目

将二进制数转换为十进制数的 Java 程序。输入是一串零和一

java - 如何将日期对象的时间设置为零 (00/00/00)

php - MySQL:今天是谁 "on"在两个不同的日期之间

java - Android AES 加密/解密结果不正确

java - Kotlin + Spring Boot,找不到 beans

javascript - 创建仅包含年份的日期对象