如何在整数日期字符串中省略 0



我已成功将日期字符串的格式从 yyyy-MM-dd 更改为 MM/dd 。现在的问题是,如果month值和day值分别小于 10,则格式应该是例如 2/7 而不是 02/07 .我该怎么做?

这是我的代码:

    public static String cahngeFormat(String dateTime) {
        Date date = null;
        String str = dateTime;
        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        try {
            date = formatter.parse(str);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(Calendar.HOUR, 2);
            formatter = new SimpleDateFormat("MM/dd");
            str = formatter.format(calendar.getTime());
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return str;
    }

将格式从 "MM/dd" 更改为 "M/d" 以允许个位数输出。

formatter = new SimpleDateFormat("M/d");
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTimeInMillis(System.currentTimeMillis());
                    String timer = formatter.format(calendar.getTime());
                    formatter.setTimeZone(java.util.TimeZone.getTimeZone("GMT"));
                    txtTimerCount.setText(formatter.format(timePassed));

我希望这对你有用。

最新更新