-1

I can convert a String to a 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;
    }
}

For example I have 200908 - it will convert to 2020-09-08, but I need set the day always to 1st day of month. I need 2020-09-01. How can I make this?

xunts
  • 102
  • 4
ip696
  • 6,574
  • 12
  • 65
  • 128
  • 3
    Keep the four first characters of your string and append `"01"` ? – Arnaud Mar 06 '18 at 08:47
  • 2
    Use the newer API for dates: https://www.mkyong.com/java8/java-8-how-to-convert-string-to-localdate/. Then it is easy to use `LocalDate`'s methods (for example `withDayOfMonth(int)`) to manipulate the date. You can also convert your `Date` to `Calendar` and set the day to one there, if you have to use `Date`. – Malte Hartwig Mar 06 '18 at 08:49
  • 2
    And a minimum of googling also produces this: [how can I change month only in java date object?](https://stackoverflow.com/questions/25347073/how-can-i-change-month-only-in-java-date-object) – Malte Hartwig Mar 06 '18 at 08:57
  • 1
    Try to avoid asking two questions in one. Better to post two questions. Your first question, convert String to date, has been asked and answered many times, please search and find your favourite answer. I would be surprised if you cannot find an answer to the second question too, setting day of month to 1. – Ole V.V. Mar 06 '18 at 09:31
  • I recommend you avoid the `SimpleDateFormat` class. It is not only long outdated, it is also notoriously troublesome. Today we have so much better in [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Mar 06 '18 at 09:32

5 Answers5

3

According to your need,you can use this method:

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;
    }
}

for date object you can use this:

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;
    }
}
aj0822ArpitJoshi
  • 1,142
  • 1
  • 9
  • 25
2
  1. Your code has multi threading issue, best create locally in your convert function to avoid it (otherwise you will have troubles with multiple thread as this class is not thread-safe)

Answer to your question is (using old Date api) - you can use Calendar to do it:

    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();
    }
Maciej
  • 1,954
  • 10
  • 14
2

Maciej's answer is correct, but if you use Java 8 or higher, it's better to use the java.time classes:

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

Note that the LocalDate is printed in the format you want - which is ISO8601 compliant. If you want a different format, just use another DateTimeFormatter and call the format method.

Manually changing the string, as suggested by others, might also work, but if you're dealing with dates, why not use a proper date-handling API? Direct string manipulation won't help you in cases like invalid dates (the formatter will throw an exception for invalid inputs), or if you try to change the day to invalid values (such as day 31 for April, or 29 for February in a non-leap year, which are checked by the API and throw an exception if the value is invalid).

xunts
  • 102
  • 4
1

you could try something like this:

String[] arr = date.split("-");
String newDate = arr[0] + "-" + arr[1] + "-01";
hensing1
  • 187
  • 13
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();
    }
}

Don’t return null from a method. The risk of a NullPointerException on the caller’s side would be great. If you believe that not returning a value is the right thing in case of a string in the wrong format or containing an invalid date, use Optional to force the caller to take the possibility of no return value into account. Another obvious option is to leave any parsing exception to the caller:

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

DateTimeParseException is an unchecked exception, so needs not be declared in the method signature. Let’s try it:

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

This prints:

2020-09

Other messages:

  • I am using and warmly recommending java.time, the modern Java date and time API. The old date-time classes from Java 1.0 and 1.1 are now long outdated, and SimpleDateFormat in particular is notoriously troublesome. I think you should avoid them. The modern API is so much nicer to work with.
  • It seems you would really prefer to remove the day of month so you only have the month and year? The YearMonth class from java.time does exactly that for you. If instead you wanted a full date, use the LocalDate class as in xunts’ answer.

Link: Oracle tutorial: Date Time explaining how to use java.time.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161