在Java中以特定格式打印日期时间?

我想以特定的格式在java中打印出datetime。 我有这个C#代码以这种格式打印出日期时间。

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

结果是 – 2010年1月18日12:00:00 AM

现在,我想写一个以相同格式打印出日期时间的java代码。 我使用了joda.time库。 这是我到目前为止所尝试的。

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

如何在java中的DateTime中将年,月和日作为构造函数传递,并以上述格式打印出来。

方法1:使用java.time.LocalDateTime 。 ( 强烈偏好

 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 

方法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 

方法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 

如果您需要24小时制日期,请使用此方法

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

请注意,在24小时制中,无需显示上午/下午。

如果您想在12小时制中使用日期,请使用以下方法

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

日期格式中的“a”将有助于显示上午/下午。

请在下面的类中导入以上代码

java.text.SimpleDateFormat中

java.util.Date

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

要么

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

如果你想加时间的话