XXXX
XXXX

Reputation: 65

Change date format from m/dd/yy to yyyy/MM/dd in Java

I have this Date in a String with a 2 digit year. I need to convert in another format. I tried with SampleDateFormat but it didn't work. The SampleDateFormat is giving wrong format i.2 date with UTC and timestamp I want in yyyy/MM/dd only. Is there any other way to do this?

String receiveDate = "7/20/21";
DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
try {
    rdate = sdf.parse(receiveDate);
} catch (ParseException e) {
    e.printStackTrace();
}
String recievedt = rdate.toString();
String dateParts[] = recievedt.split("/");
// Getting day, month, and year from receive date
String month = dateParts[0];
String day = dateParts[1];
String year = dateParts[2];

int iday = Integer.parseInt(day);
int imonth = Integer.parseInt(month);
int iyear = Integer.parseInt(year);
LocalDate date4 = LocalDate.of(iyear, imonth, iday).plusDays(2*dueoffset);

Upvotes: 2

Views: 5621

Answers (2)

Debodirno Chandra
Debodirno Chandra

Reputation: 183

How is String receiveDate="7/20/21"; a valid date?

String dateStr = "07/10/21";
SimpleDateFormat receivedFormat = new SimpleDateFormat("yy/MM/dd");
SimpleDateFormat finalFormat = new SimpleDateFormat("yyyy/MM/dd");
Date date = receivedFormat.parse(dateStr);
System.out.println(finalFormat.format(date));  // 2007/10/21

This, however, requires that you have date with leading zeros for year, month and date. If that is not the case, please sanitize your date string.

public static String sanitizeDateStr(String dateStr) {
    String dateStrArr[] = dateStr.split("/");
    String yearStr = String.format("%02d", Integer.parseInt(dateStrArr[0]));
    String monthStr = String.format("%02d", Integer.parseInt(dateStrArr[1]));
    String dayStr = String.format("%02d", Integer.parseInt(dateStrArr[2]));
    
    return String.format("%s/%s/%s", yearStr, monthStr, dayStr);
}

public static void main (String[] args) throws Exception {
    String dateStr = sanitizeDateStr("7/10/21");
    SimpleDateFormat receivedFormat = new SimpleDateFormat("yy/MM/dd");
    SimpleDateFormat finalFormat = new SimpleDateFormat("yyyy/MM/dd");
    Date date = receivedFormat.parse(dateStr);
    System.out.println(finalFormat.format(date));
}

Upvotes: 0

Chris Cooper
Chris Cooper

Reputation: 899

If you can use the java.time API I would suggest something along the lines of the following:

String input = "7/20/21";
LocalDate receivedDate = LocalDate.parse(input, DateTimeFormatter.ofPattern("M/dd/yy"));
String formatted = receivedDate.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
// or if you actually need the date components
int year = receivedDate.getYear();
...

Upvotes: 4

Related Questions