在通用时间和标准时间打印时间和日期

时间:2015-11-20 06:31:12

标签: java

编写一个将用户输入带入时间和日期类的Java应用程序,但我不确定如何获取此用户输入并将其转换为通用和标准时间...我花了几个小时浏览网页和堆栈溢出并且无法找到解决方案。

我将小时,分钟,秒,年,月,日都放在单独的整数变量中,并且需要在通用和标准时间显示它们。

谢谢你看看......

3 个答案:

答案 0 :(得分:2)

有两种解决方案: 首先将所有输入放在字符串中并解析它:

String dateStr = ""
//put your input in this string in some format/ example:
//dateSttr = year + "." + month + "." + day + " " + hour + ":" + minute;
//It is better to use StringBuilder

DateFormat inputFormat = new SimpleDateFormat("yyyy.MM.dd hh:mm");
//note that hh is 12h-format and HH is 24h-format
DateFormat outputFormat1 = new SimpleDateFormat("your_outputFormat");
DateFormat outputFormat2 = new SimpleDateFormat("your_another_outputFormat");
Date date = inputFormat.parse(dateStr);
String o1, o2;
o1 = outputFormat1.format(date);
o2 = outputFormat2.format(date);
//o1 and o2 is your result.

有关规则,如何完成此格式,请参阅javadoc

第二个解决方案是获取新日期并设置参数:

Calendar cln = Calendar.getInstance().clear(); 
//by default you get a calendar with current system time

//now set the fields. for example, day:
cln.set(Calendar.YEAR, 2015);
cln.set(Calendar.MONTH, Calendar.FEBRUARY);
cln.set(Calendar.DAY_OF_MONTH, 17);
cln.set(Calendar.HOUR_OF_DAY, 18);//Calendar.HOUR for 12h-format
cln.set(Calendar.MINUTE, 27);

详细了解如何在javadoc中设置日历 请注意,在第二个版本中,您可能会有一些字段为undefiend。

答案 1 :(得分:1)

如果@JonSkeet的假设和我的假设是正确的,那么您将以UTC或当地时间开始。显示它只是格式化输出的问题。

对于其他类型的时间,您可以添加或减去一些小时数,您可以在网上找到它们。棘手的部分是,这可能会让你进入下一个日历日,或者让你回到前一个日历日。为了解决这个问题,我想你想要

  1. 实施年,月,日,小时的加法器 - 或

  2. 将这些转换为十进制的东西(Excel使用天数,例如,在我写这个的时候是42328.08813),将值移动适当的小时数,然后将其转换回来。

答案 2 :(得分:0)

java.time

The AnswerTEXHIK是正确的,但过时了。另外,正如其他人所说,我不知道你的“通用和标准时间”是什么意思。但是我会尽力让你分道扬。

从Java 8开始,新的java.time框架取代了旧的java.util.Date/.Calendar类。新课程的灵感来自非常成功的Joda-Time框架,旨在作为其继承者,在概念上类似但重新设计。由JSR 310定义。由ThreeTen-Extra项目扩展。请参阅Tutorial

ZonedDateTime类有一个工厂方法,用于记录年,月等数字。

另外,您必须指定time zone。如果您的数字代表UTC中的日期时间,请使用ZoneOffset.UTC常量。对于其他时区,请使用适当的时区名称指定ZoneId对象;永远不要使用ESTIST等3-4个字母代码,因为它们既不标准也不唯一。

ZoneId zoneId = ZoneId.of( "America/Montreal" );
// ZoneId zoneId = ZoneOffset.UTC; // ZoneOffset is a subclass of ZoneId.
ZonedDateTime zdt = ZonedDateTime.of( 2015 , 1 , 2 , 3 , 4 , 5 , 6 , zoneId );
  

zdt:2015-01-02T03:04:05.000000006-05:00 [美国/蒙特利尔]

您可以转换为UTC或其他时区。

ZonedDateTime zdt_Kolkata = zdt.withZoneSameInstant ( ZoneId.of("Asia/Kolkata") );
ZonedDateTime zdt_Utc = zdt.withZoneSameInstant ( ZoneOffset.UTC );
  

zdt_Kolkata:2015-01-02T13:34:05.000000006 + 05:30 [亚洲/加尔各答]

     

zdt_Utc:2015-01-02T08:04:05.000000006Z

如果使用尚未针对java.time更新的类,请转换为java.util.Date。首先提取一个Instant对象,时间轴上的一个时刻始终为UTC。

java.util.Date date = java.util.Date.from ( zdt.toInstant () );