Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print "Today is May 22, 2014 and it is 2:04 pm" at the console?

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, use Calendar, here.
  • Use Date and SimpleDateFormat, 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));
like image 564
mins Avatar asked Dec 17 '25 11:12

mins


2 Answers

java.time

The legacy date-time API (java.util date-time types and their formatting API, SimpleDateFormat) is outdated and error-prone. It is recommended to stop using it completely and switch to java.time, the modern date-time API*.

Solution using modern date-time API:

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String args[]) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("'Today is' dd MMM uuuu 'and it is' HH:mm", Locale.FRENCH);
        LocalDateTime ldt = LocalDateTime.now(ZoneId.of("Europe/Paris"));
        System.out.println(dtf.format(ldt));
    }
}

Output:

Today is 05 mai 2021 and it is 11:50

Notes:

  1. Replace Locale.FRENCH with Locale.getDefault() if your JVM already has Locale.FRENCH set as the locale.
  2. Replace ZoneId.of("Europe/Paris") with ZoneId.systemDefault() or simply use LocalDateTime.now() if your JVM already has Europe/Paris set as the timezone.

For localization of the date and time formats too you may do like this:

        DateTimeFormatter dtfDate = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG);
        DateTimeFormatter dtfTime = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT);
        
        ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("Europe/Paris"));
        System.out.format("Today is %s and it is %s%n",
                zdt.format(dtfDate), zdt.format(dtfTime));

Example output with default locale Locale.FRENCH:

Today is 5 mai 2021 and it is 19:08

Example with Locale.US:

Today is May 5, 2021 and it is 7:11 PM

The latter snippet also features another difference, the use of ZonedDateTime instead of LocalDateTime. It would be advantageous under the following circumstances:

  1. If you wanted (now or at a later time) to give output in FULL format, which includes time zone and therefore requires a ZonedDateTime.
  2. If at any time you wanted to use the date-time object for anything else than printing, it’s safest that it knows its own time zone. This can prevents a range of potential errors.

Learn more about the the modern date-time API* from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

like image 68
Arvind Kumar Avinash Avatar answered Dec 19 '25 05:12

Arvind Kumar Avinash


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.

like image 41
Michael Borgwardt Avatar answered Dec 19 '25 05:12

Michael Borgwardt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!