如何打印“今天是2014年5月22日,下午2:04”在控制台? [英] How to print "Today is May 22, 2014 and it is 2:04 pm" at the console?
问题描述
所以这里是要求:
- 在控制台打印
今天是2014年5月22日,下午2:04
- 时间是由本地系统显示的当前系统(本地时间)
- 使用的日期/时间格式符合JVM区域设置,这意味着对于我在法国,这将打印
今天是22 mai 2014,它是14:04
- 外部库只是作为替代,提供一个解决方案与标准API
- 使用Java 7或更低版本。
这似乎离你好世界 难度级别,仍然困惑我在查找答案时看到的复杂性。
现在只是为了参考,这里有关于我发现的建议的信息,这让我疯狂:
- 不要使用
日期
,使用日历
, here 。 - 使用
日期
和SimpleDateFormat
,此处 - 不要使用
java.util。
{日历
,日期
},这里。 - 对于日期部分,使用
Calendar
并将时间组件设置为零,此处。 - 仅使用
System.currentTimeMillis()
获取日期和时间,这里。
编辑:解决方案提供d by Michael:
Date now = new Date();
DateFormat dateFmt = DateFormat.getDateInstance(DateFormat.LONG);
DateFormat timeFmt = DateFormat.getTimeInstance(DateFormat.SHORT);
System.out.println(今天是+ dateFmt.format(现在)+
,它是+ timeFmt.format(now));
你一定要使用新的Date()
以获取当前时间。
由于您需要本地化格式,请使用 getDateInstance()和 getTimeInstance()工厂方法 java.text。 DateFormat
来获取格式化对象。查看重载版本以更好地控制格式化风格。
这就是您需要的。
For a Java learner, this simple question is a headache. I'm quite sure a simple answer would help beginners.
So here are the requirements:
- Print at the console
Today is May 22, 2014 and it is 2:04 pm
- Where the date and time are the current ones as displayed by the local system (local time)
- Where the date/time format used is compliant with the JVM locale, meaning that for me in France this would print
Today is 22 mai 2014 and it is 14:04
- External libraries are ok only as an alternative, after providing a solution with standard APIs.
- Use Java 7 or below.
This seems not far from the "hello world" difficulty level, still I'm puzzled by the complexity of what what I've seen when searching for an answer.
Now just for reference, here are information about the suggestions I have found, and that drive me crazy:
- Don't use
Date
, useCalendar
, here. - Use
Date
andSimpleDateFormat
, here. - Don't use
java.util.
{Calendar
,Date
}, here. - For the date part, use
Calendar
and set time components to zero, here. - Use only
System.currentTimeMillis()
to get date and time, here.
Edit: the solution provided by Michael:
Date now = new Date();
DateFormat dateFmt = DateFormat.getDateInstance(DateFormat.LONG);
DateFormat timeFmt = DateFormat.getTimeInstance (DateFormat.SHORT);
System.out.println("Today is " + dateFmt.format(now) +
" and it is " + timeFmt.format(now));
You definitely want to use new Date()
to get the current time.
Since you want localized formatting, use the getDateInstance() and getTimeInstance() factory methods of java.text.DateFormat
to get formatter objects. Look at the overloaded versions for more control of the formatting style.
That's all you need.
这篇关于如何打印“今天是2014年5月22日,下午2:04”在控制台?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!