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.
- Use Java 7 or below.
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));
You definitely want to use
new Date()
to get the current time.Since you want localized formatting, use the getDateInstance() and getTimeInstance() factory methods of
java.text.DateFormat
to get formatter objects. Look at the overloaded versions for more control of the formatting style.That's all you need.
Mixing English words with localized date-time values seems peculiar. But here you go.
Avoid java.util.Date/Calendar
The java.util.Date and .Calendar classes bundled with Java are notoriously troublesome. Avoid them. Use a decent date-time library instead, such as Joda-Time or the new java.time package in Java 8.
Time Zone
Your question ignores the crucial issue of time zone.
Joda-Time
Example code in Joda-Time 2.3.
Try this code
df is the Formater for date, tf is the formater for the time string.
Try this (which uses the default JVM locale):
If you need a different locale you can force it like follows:
Or you can update the locale of the JVM to override the system one: how do I set the default locale for my JVM?
Go ahead and use Date and SimpleFormat. To get things in the format that you need, you can always call a String.split( X ) on the date string to get at the different pieces you need. Once you have those pieces it should be relatively simple to print the info you need