Java(Groovy) 與 C 日期處理的對照

C 語言

  struct tm* my_time;
  int data = 1317789160        // 秒數
  my_time = localtime(data)
  assert(111==my_time.tm_year)    // 自 1900 起算,正確年份計算: 111+1900=2011
  assert(9  ==my_time.tm_mon)     // 0..11
  assert(4  ==my_time.tm_mday)    // 1..31
  assert(2  ==my_time.tm_wday)    // 0..6
  assert(276==my_time.tm_yday)    // 0..365

Java(Groovy)

  Integer data = 1317789160     // 秒數
  Date my_date = new Date(data * 1000)        // 毫秒
  assert 2011, my_date.getAt(Calendar.YEAR)
  assert 9, my_date.getAt(Calendar.MONTH)            // 0..11
  assert 4, my_date.getAt(Calendar.DAY_OF_MONTH)     // 1..31
  assert 3, my_date.getAt(Calendar.DAY_OF_WEEK)      // 1..7
  assert 277, my_date.getAt(Calendar.DAY_OF_YEAR)    // 1..366

註: Date.getAt(int) 是 Groovy API

以上可以看出兩者的差異:
C的年份是用累積的方式,自1900年開始,因此要加上 1900 才能得出正確的年份。其他的差不多,差別在由 0 開始算還是由 1 開始算。不過因為不統一有點難記住。

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s