[英]Printing out datetime in a specific format in Java?
I want to print out datetime in java in a specific format.我想以特定格式在java中打印日期时间。 I have this C# code which prints out the datetime in this format.
我有这个 C# 代码,它以这种格式打印出日期时间。
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结果是 - 1/18/2010 12:00:00 AM
Now, I want to write a java code that prints out the datetime in the same format.现在,我想编写一个 java 代码,以相同的格式打印出日期时间。 I used the joda.time library.
我使用了 joda.time 库。 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.如何在java中的DateTime中将年月日作为构造函数传递并以上述格式打印出来。
Approach 1: Using java.time.LocalDateTime .方法 1:使用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 .方法 2:使用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 .方法 3:使用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如果您需要 24 小时制的日期,请使用此方法
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.请注意,在 24 小时制中,无需显示 AM/PM。
If you want date in 12 hour system then use below approach如果您想要 12 小时制的日期,请使用以下方法
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.日期格式中的“a”将有助于显示 AM/PM。
Please import below classes for above code to work请导入以下类以使上述代码工作
java.text.SimpleDateFormat
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"));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.