Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing out datetime in a specific format in Java?

Tags:

java

I want to print out datetime in java in a specific format. I have this C# code which prints out the datetime in this format.

DateTime value = new DateTime(2010, 1, 18);
Console.WriteLine(value);
Console.WriteLine(value == DateTime.Today);

The result is - 1/18/2010 12:00:00 AM

Now, I want to write a java code that prints out the datetime in the same format. I used the joda.time library. This is what I tried so far.

DateTime today = new DateTime();
System.out.println(today.toString(“yyyy-MMM-dd”));

How can I pass the year,month and day as the constructor in the DateTime in java and print out in the above format.

like image 348
Farheen Avatar asked Nov 21 '16 08:11

Farheen


2 Answers

Approach 1: Using java.time.LocalDateTime. (Strongly Preferred)

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
System.out.println(dtf.format(now)); //2016/11/16 12:08:43

Approach 2: Using java.util.Date.

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date)); //2016/11/16 12:08:43

Approach 3: Using java.util.Calendar.

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal)); //2016/11/16 12:08:43
like image 92
Wasi Ahmad Avatar answered Oct 08 '22 21:10

Wasi Ahmad


If you need date in 24 hour system then use this approach

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date custDate = new Date();
System.out.println(sdf.format(custDate));

Please note in 24 hour system there is no need to show AM/PM.

If you want date in 12 hour system then use below approach

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
Date custDate = new Date();
System.out.println(sdf.format(custDate));

"a" in the date format will help to show AM/PM.

Please import below classes for above code to work

java.text.SimpleDateFormat

java.util.Date

like image 30
SachinSarawgi Avatar answered Oct 08 '22 19:10

SachinSarawgi