首页 > 代码 > 常规代码 > 正文

代码

阅读排行

Unix时间戳(since1970)与日期之间互相转换
2014-06-21 21:12:58   来源:Fcode研讨团队   评论:0 点击:

此代码实现了Unix时间戳(Seconds since 1970)与时间日期之间的转换。符合语法规范,可在主流编译器上运行。

如下代码,输出为:

Unix Time:1403298617   0x53A4A339
 Date:        2014           6          20          21          10          17


注意:最高可支持到2038年1月19日03:14:07
Program www_fcode_cn
  Implicit None
  Integer :: i
  Integer :: year=0 , mon=0 , day=0 , hour=0 , min=0 , sec=0
  call Date2UnixTime( 2014 , 6 , 20 , 21 , 10 , 17 , i )
  write(*,'(a,g0,3x,a,z8)') 'Unix Time:' , i  , '0x' , i
  call UnixTime2Date( i, year , mon , day , hour , min , sec )
  write(*,*) 'Date:' , year , mon , day , hour , min , sec
End Program www_fcode_cn    

Subroutine UnixTime2Date( iUnixTime, year , mon , day , hour , min , sec )
  !// Convert UnixTime ( Seconds since 1970 ) to Date and time  
  !// Range From 1970 to January 19, 2038 03:14:07
  !// write by gao@fcode.cn @@ www.fcode.cn
  Implicit None
  Integer , Intent(IN) :: iUnixTime
  Integer , Intent(OUT) :: year , mon , day , hour , min , sec
  integer uDays , uSecs , mDay , n
  real rDay
  uDays = int(iUnixTime/86400)
  uSecs = mod(iUnixTime,86400)
  mDay = uDays + 40587
  year = 1858 + int( (mDay + 321.51) / 365.25)
  rDay = aint( mod(mDay + 262.25, 365.25) ) + 0.5
  mon  = 1 + int(mod(rDay / 30.6 + 2.0, 12.0) )
  day  = 1 + int(mod(rDay,30.6))
  n    = uSecs
  sec = mod(n, 60)
  n    = n / 60
  min  = mod(n, 60)
  hour  = n / 60
End Subroutine UnixTime2Date

Subroutine Date2UnixTime( year , mon , day , hour , min , sec , iUnixTime )
  !// Convert Date and time to UnixTime ( Seconds since 1970 )
  !// Range From 1970 to January 19, 2038 03:14:07
  !// write by gao@fcode.cn @@ www.fcode.cn
  Implicit None
  Integer , Intent(IN) :: year , mon , day , hour , min , sec
  Integer , Intent(OUT) :: iUnixTime
  integer :: iy , im
  integer :: a
  real :: jd
  if ( mon > 2 ) then
    iy = year
    im = mon
  else
    iy = year - 1
    im = mon + 12
  end if
  a = INT(iy / 100)
  a = 2 - a + INT(a/4)
  JD = INT(365.25*(iy + 4716)) + INT(30.60001*(im + 1)) + day + a -1524.5
  iUnixTime = Int( (JD-2440587.5)*86400) + hour*3600 + min*60 + sec
End Subroutine Date2UnixTime

相关热词搜索:Unix时间戳

上一篇:计算圆周率 PI 任意位数
下一篇:任意大小数组平均成任意大小数组

分享到: 收藏