For a Java learner, this simple question is a headache. I'm quite sure a simple answer would help beginners.
So here are the requirements:
- Print at the console
Today is May 22, 2014 and it is 2:04 pm
- Where the date and time are the current ones as displayed by the local system (local time)
- Where the date/time format used is compliant with the JVM locale, meaning that for me in France this would print
Today is 22 mai 2014 and it is 14:04
- External libraries are ok only as an alternative, after providing a solution with standard APIs.
This seems not far from the "hello world" difficulty level, still I'm puzzled by the complexity of what what I've seen when searching for an answer.
Now just for reference, here are information about the suggestions I have found, and that drive me crazy:
- Don't use
Date
, useCalendar
, here. - Use
Date
andSimpleDateFormat
, here. - Don't use
java.util.
{Calendar
,Date
}, here. - For the date part, use
Calendar
and set time components to zero, here. - Use only
System.currentTimeMillis()
to get date and time, here.
Edit: the solution provided by Michael:
Date now = new Date();
DateFormat dateFmt = DateFormat.getDateInstance(DateFormat.LONG);
DateFormat timeFmt = DateFormat.getTimeInstance (DateFormat.SHORT);
System.out.println("Today is " + dateFmt.format(now) +
" and it is " + timeFmt.format(now));