D. Elliott D. Elliott - 23 days ago 7
Java Question

Convert date to dd/MM/yyyy in Java

I am trying to get my calendar to print what day it is in dd/MM/yyyy format, but it just doesn't seem to work.

My code is:

SimpleDateFormat form = new SimpleDateFormat("dd/MM/yy", Locale.ENGLISH);
Date now = new Date("19/11/16");
form.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(form.format(now));
Calendar cal = Calendar.getInstance();
cal.setTime(now);
System.out.println(cal.get((Calendar.DAY_OF_WEEK)));

if(cal.get((Calendar.DAY_OF_WEEK)) < 7 || cal.get((Calendar.DAY_OF_WEEK)) > 1) {
System.out.println("It's a weekday");
}
else {
System.out.println("It's a weekend");
}


And the output is:


10/07/17

3

It's a weekday


Can anyone spot the issue?

Answer

The Date constructor you are calling is creating a Date with the wrong fields, to initialize your Date with your format parse the String. Like

Date now = form.parse("19/11/16");

Making sure to either catch (or rethrow) ParseException. With those two changes I then get

19/11/16
7
It's a weekday