相关的问题是“Datetime到Unix时间戳”,但这个问题更一般。

我需要Unix时间戳来解决最后一个问题。我的兴趣是Python、Ruby和Haskell,但也欢迎其他方法。

生成Unix时间戳最简单的方法是什么?


当前回答

public static Int32 GetTimeStamp()
    {
        try
        {
            Int32 unixTimeStamp;
            DateTime currentTime = DateTime.Now;
            DateTime zuluTime = currentTime.ToUniversalTime();
            DateTime unixEpoch = new DateTime(1970, 1, 1);
            unixTimeStamp = (Int32)(zuluTime.Subtract(unixEpoch)).TotalSeconds;
            return unixTimeStamp;
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex);
            return 0;
        }
    }

其他回答

让我们试试JavaScript:

var t = Math.floor((new Date().getTime()) / 1000);

...或者更好的静态方法:

var t = Math.floor(Date.now() / 1000);

在这两种情况下,我都用1000从秒到毫秒,我使用数学。只表示已经过的整秒(与舍入相比,舍入可能表示尚未经过的整秒)。

如果我想打印utc日期时间使用日期命令,我需要使用-u参数与日期命令。

例子

date -u

输出

Fri Jun 14 09:00:42 UTC 2019

在Bash 5中有一个新变量:

echo $EPOCHSECONDS

或者如果你想要更高的精度(以微秒为单位):

echo $EPOCHREALTIME

在Ruby中:

>> Time.now.to_i
=> 1248933648

对于类unix环境,以下操作可以工作。

# Current UNIXTIME
unixtime() {
  datetime2unixtime "$(date -u +'%Y-%m-%d %H:%M:%S')"
}

# From DateTime(%Y-%m-%d %H:%M:%S)to UNIXTIME
datetime2unixtime() {
  set -- "${1%% *}" "${1##* }"
  set -- "${1%%-*}" "${1#*-}" "${2%%:*}" "${2#*:}"
  set -- "$1" "${2%%-*}" "${2#*-}" "$3" "${4%%:*}" "${4#*:}"
  set -- "$1" "${2#0}" "${3#0}" "${4#0}" "${5#0}" "${6#0}"
  [ "$2" -lt 3 ] && set -- $(( $1-1 )) $(( $2+12 )) "$3" "$4" "$5" "$6"
  set -- $(( (365*$1)+($1/4)-($1/100)+($1/400) )) "$2" "$3" "$4" "$5" "$6"
  set -- "$1" $(( (306*($2+1)/10)-428 )) "$3" "$4" "$5" "$6"
  set -- $(( ($1+$2+$3-719163)*86400+$4*3600+$5*60+$6 ))
  echo "$1"
}

# From UNIXTIME to DateTime format(%Y-%m-%d %H:%M:%S)
unixtime2datetime() {
  set -- $(( $1%86400 )) $(( $1/86400+719468 )) 146097 36524 1461
  set -- "$1" "$2" $(( $2-(($2+2+3*$2/$3)/$5)+($2-$2/$3)/$4-(($2+1)/$3) ))
  set -- "$1" "$2" $(( $3/365 ))
  set -- "$@" $(( $2-( (365*$3)+($3/4)-($3/100)+($3/400) ) ))
  set -- "$@" $(( ($4-($4+20)/50)/30 ))
  set -- "$@" $(( 12*$3+$5+2 ))
  set -- "$1" $(( $6/12 )) $(( $6%12+1 )) $(( $4-(30*$5+3*($5+4)/5-2)+1 ))
  set -- "$2" "$3" "$4" $(( $1/3600 )) $(( $1%3600 ))
  set -- "$1" "$2" "$3" "$4" $(( $5/60 )) $(( $5%60 ))
  printf "%04d-%02d-%02d %02d:%02d:%02d\n" "$@"
}

# Examples
unixtime # => Current UNIXTIME
date +%s # Linux command

datetime2unixtime "2020-07-01 09:03:13" # => 1593594193
date -u +%s --date "2020-07-01 09:03:13" # Linux command

unixtime2datetime "1593594193" # => 2020-07-01 09:03:13
date -u --date @1593594193 +"%Y-%m-%d %H:%M:%S" # Linux command

https://tech.io/snippet/a3dWEQY