将字符串转换为日期并删除日期值(始终设置为1个月中的某一天)

时间:2018-03-06 08:45:15

标签: java date date-parsing date-manipulation dayofmonth

我可以将String转换为Date

private static final SimpleDateFormat CARD_DATE_FORMAT = new SimpleDateFormat("yyMMdd", Locale.getDefault());

public static Date toCardDateFormat(String date){
    try {
        return CARD_DATE_FORMAT.parse(date);
    } catch (ParseException e) {
        return null;
    }
}

例如,我有200908 - 它会转换为2020-09-08,但我需要将每天的日期设置为1 st 。我需要2020-09-01。我该怎么做?

5 个答案:

答案 0 :(得分:3)

根据您的需要,您可以使用此方法:

private static final SimpleDateFormat CARD_DATE_FORMAT = new SimpleDateFormat("yyMMdd", Locale.getDefault());

public static String toCardDateFormat(String date) {
    try {
        Date value = CARD_DATE_FORMAT.parse(date);
        SimpleDateFormat dateFormatter = new SimpleDateFormat("yy-MM", Locale.getDefault());

        String datetimeLocale = dateFormatter.format(value);
        String newDate = datetimeLocale + "-01";
        return newDate;
    } catch (ParseException e) {
        return null;
    }
}

对于日期对象,您可以使用它:

public static Date toCardDateFormat(String date) {
    try {
        Date value = CARD_DATE_FORMAT.parse(date);
        SimpleDateFormat dateFormatter = new SimpleDateFormat("yy-MM", Locale.getDefault());

        String datetimeLocale = dateFormatter.format(value);
        String newDate = datetimeLocale + "-01";

        SimpleDateFormat dateFormat = new SimpleDateFormat("yy-MM-dd",Locale.getDefault());
        Date d = dateFormat.parse(newDate);


        return d;
    } catch (ParseException e) {
        return null;
    }
}

答案 1 :(得分:2)

  1. 您的代码存在多线程问题,最好在转换函数中本地创建以避免它(否则您将遇到多线程的麻烦,因为此类不是线程安全的)
  2. 回答你的问题是(使用旧的日期api) - 你可以使用日历来执行此操作:

        public static Date toCardDateFormat(String date){
            Date result = null;
            try {
                result = new SimpleDateFormat("yyMMdd", Locale.getDefault()).parse(date);
            } catch (ParseException e) {
                return null; // or better throw exception or return Optional.empty()
            }
    
            Calendar cal = Calendar.getInstance();
            cal.setTime(result);
            cal.set(Calendar.DAY_OF_MONTH, 1);
            return cal.getTime();
        }
    

答案 2 :(得分:2)

Maciej的回答是正确的,但如果你使用Java 8或更高版本,最好使用 java.time 类:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyMMdd");

// parse and change the day of month
LocalDate d = LocalDate.parse("200908", formatter).withDayOfMonth(1);

System.out.println(d); // 2020-09-01

请注意,LocalDate以您想要的格式打印 - 符合ISO8601标准。如果您需要其他格式,只需使用其他DateTimeFormatter并调用format方法。

按照其他人的建议手动更改字符串也可能有效,但如果您正在处理日期,为什么不使用正确的日期处理API?直接字符串操作在无效日期(格式化程序将针对无效输入引发异常)或者您尝试将日期更改为无效值(例如4月的第31天或2月的29)时无法帮助您在非闰年中,由API检查并在值无效时抛出异常。)

答案 3 :(得分:1)

你可以尝试这样的事情:

String[] arr = date.split("-");
String newDate = arr[0] + "-" + arr[1] + "-01";

答案 4 :(得分:1)

private static final DateTimeFormatter CARD_DATE_FORMAT
        = DateTimeFormatter.ofPattern("yyMMdd", Locale.getDefault());

public static Optional<YearMonth> toCardDateFormat(String date) {
    try {
        return Optional.of(YearMonth.parse(date, CARD_DATE_FORMAT));
    } catch (DateTimeParseException e) {
        return Optional.empty();
    }
}

不要从方法返回null。调用方的NullPointerException风险很大。如果您认为如果字符串格式错误或包含无效日期,则不返回值是正确的,请使用Optional强制调用者考虑无返回值的可能性。另一个明显的选择是将任何解析异常留给调用者:

public static YearMonth toCardDateFormat(String date) {
    return YearMonth.parse(date, CARD_DATE_FORMAT);
}

DateTimeParseException是未经检查的异常,因此无需在方法签名中声明。我们来试试吧:

    System.out.println(toCardDateFormat("200908"));

打印:

  

2020-09

其他讯息:

  • 我正在使用并热烈推荐java.time,即现代Java日期和时间API。 Java 1.0和1.1中的旧日期时间类现在已经过时了,特别是SimpleDateFormat非常麻烦。我认为你应该避免它们。现代API可以更好地使用。
  • 看来你真的更喜欢删除一个月中的某一天,所以你只有月份和年份? java.time中的YearMonth类完全适合您。如果您想要完整日期,请使用xunts’ answer中的LocalDate课程。

链接: Oracle tutorial: Date Time解释如何使用java.time

相关问题