Java如何添加时间和日期 [英] Java how to add time and date

查看:360
本文介绍了Java如何添加时间和日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用JDK 1.8
我有一天的时间(不是自1970年以来),而且我有一个日期我如何添加两个并创建一个日期时间。

Using JDK 1.8 I have Time in ms for a day (not since 1970) and I have a Date how do I add the two and create a datetime.

感谢
尝试@Kikos soln不会产生正确的结果:
不知何故我的原始时间930小时在这种情况下更改为9:40,原始日期本身不应该有任何时间获取时间??) - 所以添加数学失败。

Thanks Tried @Kikos soln does not produce correct result: Somehow my orig time 930 hrs in this case changes to 9:40, the orig date itself should not have any time gets time (??) - so the addition math fails.

   String testdate = "2015/10/25";
    Date date = new SimpleDateFormat("yyyy/mm/dd").parse(testdate);

    String timehrs= "930";
    long ltime = Long.parseLong("930");
    long hoursAsSeconds = (ltime / 100) * 60 * 60;
    long minsAsSeconds = (ltime % 100) * 60;
    long secondsOfDay = hoursAsSeconds + minsAsSeconds;

    System.out.println("testdate : "+ testdate +", timehrs: "+timehrs+" ,secondsOfDay: "+secondsOfDay); 
    System.out.println("Orig Date time formatted: "+ new SimpleDateFormat("yyyy-mm-dd hh:mm:ss").format(date));

    Date dt = new Date(date.getTime() + secondsOfDay*1000);

    System.out.println("New Date : "+ new SimpleDateFormat("yyyy-mm-dd hh:mm:ss").format(dt);  

testdate:2015/10/25,timehrs:930,secondsOfDay:34200
原始日期格式化时间:2015-10-25 12:10:00
新日期:2015-40-25 09:40:00

预计:2015- 10-25 09:30:00

testdate : 2015/10/25, timehrs: 930, secondsOfDay: 34200 Orig Date time formatted: 2015-10-25 12:10:00 New Date : 2015-40-25 09:40:00
Expected : 2015-10-25 09:30:00


  1. 根据下面的@Basil Bourque

  1. Based on below by @Basil Bourque

long nanosOfDay = TimeUnit.MILLISECONDS.toNanos(secondsOfDay * 1000);

LocalTime lt = LocalTime.ofNanoOfDay(nanosOfDay);
ZoneId z = ZoneId.systemDefault();
ZonedDateTime zdt = ZonedDateTime.of(ld,lt,z);

long nanosOfDay = TimeUnit.MILLISECONDS.toNanos( secondsOfDay*1000 );
LocalTime lt = LocalTime.ofNanoOfDay( nanosOfDay ); ZoneId z = ZoneId.systemDefault(); ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z );

System.out.println(ZonedDateTime zdt :+ zdt;

System.out.println("ZonedDateTime zdt: "+ zdt);

ZonedDateTime zdt:2015-10-25T09:30-07:00 [America / Los_Angeles]

ZonedDateTime zdt: 2015-10-25T09:30-07:00[America/Los_Angeles]

这是正确的答案: 2015-10-25T09:30

推荐答案

任务离子被卷曲



你说你有一天的时间是从午夜以来的毫秒数(显然)。但是 930 将意味着 00:00:00.930 而不是 09:30:00 ,如您的示例数据所示。我将按照您的文本而不是您的示例数据。

Question is convoluted

You say you have time of day as a count of milliseconds since midnight (apparently). Yet 930 would mean the time 00:00:00.930, not 09:30:00 as shown in your example data. I will follow your text rather than your example data.

您正在使用麻烦的旧日期时间类,现在是传统的,由java.time类替代。忘了你听说过 java.util.Date .Calendar

You are using troublesome old date-time classes, now legacy, supplanted by the java.time classes. Forget you ever heard of java.util.Date and .Calendar.

LocalDate 类代表只有日期的值,没有时间 - 日期,没有时区。

The LocalDate class represents a date-only value without time-of-day and without time zone.

时区对于确定日期至关重要。对于任何给定的时刻,日期根据地区而异。例如,巴黎法国午夜后的几分钟是一个新的一天,而昨天在蒙特利尔魁北克省

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still "yesterday" in Montréal Québec.

ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );



ISO 8601



java.time当解析/生成表示日期时间值的字符串时,类默认使用ISO 8601标准。要使输入字符串标准化,请用连字符替换这些斜杠字符。

ISO 8601

The java.time classes use the ISO 8601 standard by default when parsing/generating strings representing date-time values. To make your input string standard, replace those slash characters with hyphens.

String input = "2015/10/25".replace( "/" , "-" );
LocalDate ld = LocalDate.parse( input );

顺便说一句,你分配的这个整个方案是尴尬,容易出错,不必要的复杂。要序列化系统间通信的日期时间值,请使用ISO 8601字符串格式。

By the way, this whole scheme you have been assigned is awkward, error-prone, and needlessly complicated. To serialize a date-time value for communication between systems, use the ISO 8601 string formats.

你说你有一个毫秒数,代表从午夜算起的时间。

You say you have a count of milliseconds to represent the time of day as a count from midnight.

LocalTime 类提供了基于整个持续时间实例化的工厂方法和的纳秒。要获得纳秒,只需将您的毫秒增加一千。更好的是,让 TimeUnit 枚举这些工作,使您的代码更加自我记录。

The LocalTime class offers factory methods to instantiate based on a duration of whole seconds and of nanoseconds. To get nanoseconds, simply multiply your milliseconds by one thousand. Better yet, let the TimeUnit enum do the work and make your code more self-documenting.

long millisOfDay = Long.parseLong( "930" );
long nanosOfDay = TimeUnit.MILLISECONDS.toNanos( millisOfDay );  // Same effect as: ( millisOfDay * 1_000L )
LocalTime lt = LocalTime.ofNanoOfDay( nanosOfDay );



ZonedDateTime



现在将这两个 Local ... 对象以及时区组合起来,以确定时间轴上的一个点。这个日期和时间意味着在蒙特利尔魁北克,法国巴黎,加尔各答印度还是新西兰奥克兰吗?

ZonedDateTime

Now combine these two Local… objects along with a time zone to determine a point on the timeline. Was this date and time meant to be a moment in Montréal Québec, Paris France, Kolkata India, or Aukland New Zealand?

ZoneId z = ZoneId.of( "Pacific/Auckland" );
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z );

请参阅 IdeOne.com中的实时代码


ld.toString():2015-10-25

ld.toString(): 2015-10-25

lt.toString():00:00:00.930

lt.toString(): 00:00:00.930

zdt.toString():2015-10-25T00:00 :00.930 + 13:00 [太平洋/奥克兰]

zdt.toString(): 2015-10-25T00:00:00.930+13:00[Pacific/Auckland]



LocalDateTime h1>

如果您的数据没有关于时区的信息,并且您不能安全地假定您的业务场景中的预期时区,那么您将没有更好的选择, code> LocalDateTime 对象。但请记住,这个值是不明确的。该值不是时间轴上的一个点。该值表示时间线上的潜在点,只能用时区确定分配给 ZonedDateTime 从UTC分配的UTC 对于 OffsetDateTime

LocalDateTime

If your data came with no information about time zone, and you cannot safely assume the intended time zone by your business scenario, you are left with no better option than combining into a LocalDateTime object. But keep in mind that this value is ambiguous. This value is not a point on the timeline. This value represents potential points on the timeline which can only be determined with a time zone assigned for ZonedDateTime or a offset-from-UTC assigned for OffsetDateTime.

LocalDateTime ldt = LocalDateTime.of( ld , lt );






关于java.time



java.time 框架内置于Java 8及更高版本中。这些课程取代了麻烦的旧旧版日期时间课程,例如 java.util.Date 日历 ,& SimpleDateFormat


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

Joda-Time 项目,现在在维护模式中,建议迁移到java.time 。

The Joda-Time project, now in maintenance mode, advises migration to java.time.

要了解更多信息,请参阅 Oracle教程。并搜索Stack Overflow的许多示例和解释。规格为 JSR 310

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

哪里可以获取java.time类?

Where to obtain the java.time classes?


  • Java SE 8 SE 9 和更高版本


    • 内置。

    • 具有捆绑实现的标准Java API的一部分。

    • Java 9添加了一些次要功能和修复程序。

    • Java SE 8 and SE 9 and later
      • Built-in.
      • Part of the standard Java API with a bundled implementation.
      • Java 9 adds some minor features and fixes.
      • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
      • The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
      • See How to use….

      ThreeTen-Extra 项目扩展了java.time和其他类。这个项目是未来可能添加到java.time的证明。您可能会在这里找到一些有用的课程,例如 Interval YearWeek YearQuarter 更多

      The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

      这篇关于Java如何添加时间和日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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