【问题标题】:Simple fast way to convert 03/03/2015 to 3/3/2015将 03/03/2015 转换为 3/3/2015 的简单快速方法
【发布时间】:2015-05-17 17:59:35
【问题描述】:

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

    }

}

输出:

2015 年 2 月 28 日 2015 年 3 月 1 日 2015 年 3 月 2 日 2015 年 3 月 3 日

我需要:

2015 年 2 月 28 日 2015 年 3 月 1 日 2015 年 3 月 2 日 2015 年 3 月 3 日

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

【问题讨论】:

  • 文档建议使用d 而不是dd;这行得通吗?

标签: java date converter


【解决方案1】:

以下就足够了:

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

引用自java docs:

数字:对于格式化,模式字母的数量是最小位数,较短的数字会被零填充到这个数量。解析时,模式字母的数量会被忽略,除非需要分隔两个相邻的字段。

【讨论】:

    【解决方案2】:

    @JuniorCompressor 的回答是最佳选择,我的理解是,如果可以这样做,您需要将给定日期转换为所需格式:

    if(ds.startsWith("0")
       ds = ds.replaceFirst("0", "");
    
    ds = ds.replaceAll("/0", "/");
    

    【讨论】:

      【解决方案3】:

      用一个格式化程序解析它,然后用另一个格式化:

      Date date = new SimpleDateFormat("MM/dd/yyyy").parse("02/02/1984");
      String formatted = new SimpleDateFormat("M/d/yyyy").format(date);
      

      formatted 变量是"2/2/1984"

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-04-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-19
        • 2018-05-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多