在Java中以特定格式打印日期时间? [英] Printing out datetime in a specific format in Java?

查看:123
本文介绍了在Java中以特定格式打印日期时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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);

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

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

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

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"));

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

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

推荐答案

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

这篇关于在Java中以特定格式打印日期时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆