【Learning】Java Date and Time

1. There are four commonly used date time classes in Java: 
1.1 java.util.Date
1.2 java.sql.Date
1.3 java.sql.Timestamp
1.4 java.util.Calendar. 
2. sql.Date and sql.Timestamp both extends util.Date

3. Concepts:
3.1 Epoch: which is January 1, 1970 00:00:00.000 GMT
3.2 Unix Time: the number of milliseconds since the epoch, it represents an exact time/point regardless of time zones.
4. These date time clesses are just wrapper on top of a long number, which is the unix time.

5. These date time classes commonly can be instantiated in three ways:
5.1 Input a Unix time number
5.2 Input a String representation of a date time
5.3 Input (YEAR, MON, DAY, HOUR, MIN. SEC) as ints
6. Note that the Unix time number always determines an exact point, but the representation of the point, i.e. (YEAR, MON, DAY, HOUR, MIN. SEC), is dependent on current time zone. 

7. Now let's say, if we have two machines running on different time zones, one in EST, the other in CST. Given the same inputs to Date/Timestamp, would they represent the same exact point?
7.1 If we input the same Unix time number. Suppose on EST machine, the representation of the result time is 2013-03-15 18:00:00. Then on CST machine, the representation will be 2013-03-16 06:00:00. So the same Unix time number leads to two different time representations according to time zones. However, you can see that the two time representations actually refer to the same exact point, as 2013-03-15 18:00:00 EST equals to 2013-03-16 06:00:00 CST.
7.2 If we input the same String representation of a date time. Suppose we input (2013 03-15 18:00:00) on EST machine, then the Unix time number will be calculated based on EST, say the result number is A. Then we input the same String on CST machine. The result time will be A+ CST_To_EST_Offset. You can see that even though you provide the same String representation, the result two Date objects refer to different exact points, as their Unix time numbers are different.
7.3 If we input (YEAR, MON, DAY, HOUR, MIN. SEC) as intsm, say (2013, 3, 15, 18, 0, 0). The result is similar to that of 7.2.
8. Based on the analysis in point 7, we can see that if you want to pass time object between distributed components, you should be careful. Normally, it is safe to pass the Unix time number, as it always represents the same exact point, regardless of time zone. 

9. Calendar class is a bit different. One of its power is that it can calculate the Unix time number based on a given time zone rather than default time zone, which means you can specify String along with a time zone to Calendar and Calendar will calculate based on your given time zone.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值