简体   繁体   中英

Printing out datetime in a specific format in 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.

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

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

LocalDate.of(2010, 1, 18).atStartOfDay().format(DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss a"))

or

LocalDate.of(2010, 1, 18).atTime(12, 0, 0).format(DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss a"));

if you want to add the time too

Please try to this one

public void Method(Datetime time)
{
    
    time.toString("yyyy-MM-dd'T'HH:mm:ss"));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM