C# UnixTime 和 DateTime 互相轉換 函數庫

C# UnixTime 和 DateTime 互相轉換 函數庫

C# UnixTime 和 DateTime 互相轉換 函數庫


資料來源: https://stackoverflow.com/questions/249760/how-can-i-convert-a-unix-timestamp-to-datetime-and-vice-versa

https://ourcodeworld.com/articles/read/865/how-to-convert-an-unixtime-to-datetime-class-and-viceversa-in-c-sharp
https://www.epochconverter.com/
https://stackoverflow.com/questions/3354893/how-can-i-convert-a-datetime-to-the-number-of-seconds-since-1970


Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CS_VPOS
{
    public class TimeConvert
    {
        //https://stackoverflow.com/questions/249760/how-can-i-convert-a-unix-timestamp-to-datetime-and-vice-versa
        public static DateTime UnixTimeStampToDateTime(double unixTimeStamp)
        {
            // Unix timestamp is seconds past epoch
            DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            dateTime = dateTime.AddSeconds(unixTimeStamp).ToLocalTime();
            return dateTime;
        }
        
        //https://ourcodeworld.com/articles/read/865/how-to-convert-an-unixtime-to-datetime-class-and-viceversa-in-c-sharp
        public static long DateTimeToUnixTimeStamp(DateTime MyDateTime)
        {
            /*
            TimeSpan timeSpan = MyDateTime - new DateTime(1970, 1, 1, 0, 0, 0);
            return (long)(timeSpan.TotalSeconds-8*60*60);//8*60*60 來源: GMT+08:00 ~ https://www.epochconverter.com/
            */

            DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            TimeSpan diff = MyDateTime.ToUniversalTime() - origin;
            return (long)(diff.TotalSeconds);//https://stackoverflow.com/questions/3354893/how-can-i-convert-a-datetime-to-the-number-of-seconds-since-1970
        }

        public static DateTime JavaTimeStampToDateTime(double javaTimeStamp)
        {
            // Java timestamp is milliseconds past epoch
            DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            dateTime = dateTime.AddMilliseconds(javaTimeStamp).ToLocalTime();
            return dateTime;
        }
    }//TimeConvert
}

3 thoughts on “C# UnixTime 和 DateTime 互相轉換 函數庫

    1. Unix Time(時間) 線上轉換工具 列舉(包含) 市面上常用程式語言 撰寫 教學

      PHP time() More PHP
      Python import time; time.time() Source
      Ruby Time.now (or Time.new). To display the epoch: Time.now.to_i
      Perl time More Perl
      Java long epoch = System.currentTimeMillis()/1000; Returns epoch in seconds.
      C# DateTimeOffset.Now.ToUnixTimeSeconds() (.NET Framework 4.6+/.NET Core), older versions: var epoch = (DateTime.UtcNow – new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;
      Objective-C [[NSDate date] timeIntervalSince1970]; (returns double) or NSString *currentTimestamp = [NSString stringWithFormat:@”%f”, [[NSDate date] timeIntervalSince1970]];
      C++11 double now = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count();
      Lua epoch = os.time([date])
      VBScript/ASP See the examples
      AutoIT _DateDiff(‘s’, “1970/01/01 00:00:00”, _NowCalc())
      Delphi Epoch := DateTimetoUnix(Now); Tested in Delphi 2010.
      R as.numeric(Sys.time())
      Erlang/OTP erlang:system_time(seconds). (version 18+), older versions: calendar:datetime_to_gregorian_seconds(calendar:universal_time())-719528*24*3600.
      MySQL SELECT unix_timestamp(now()) More MySQL examples
      PostgreSQL SELECT extract(epoch FROM now());
      SQLite SELECT strftime(‘%s’, ‘now’);
      Oracle PL/SQL SELECT (CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS DATE) – TO_DATE(’01/01/1970′,’DD/MM/YYYY’)) * 24 * 60 * 60 FROM DUAL;
      SQL Server SELECT DATEDIFF(s, ‘1970-01-01 00:00:00’, GETUTCDATE())
      IBM Informix SELECT dbinfo(‘utc_current’) FROM sysmaster:sysdual;
      JavaScript Math.floor(new Date().getTime()/1000.0) The getTime method returns the time in milliseconds.
      Visual FoxPro DATETIME() – {^1970/01/01 00:00:00} Warning: time zones not handled correctly
      Go time.Now().Unix() More Go
      Adobe ColdFusion
      Tcl/Tk clock seconds
      Unix/Linux Shell date +%s
      Solaris /usr/bin/nawk ‘BEGIN {print srand()}’ Solaris doesn’t support date +%s, but the default seed value for nawk’s random-number generator is the number of seconds since the epoch.
      PowerShell [int][double]::Parse((Get-Date (get-date).touniversaltime() -UFormat %s))
      Other OS’s Command line: perl -e “print time” (If Perl is installed on your system)

  1. C#中系統時間和UNIX時間戳互相轉換
    c# DateTime时间格式与Unix时间戳格式
    Datetime 與Unix 時間戳記轉換
    DateTimeOffset.ToUnixTimeSeconds
    C# DateTime與時間戳轉換
    時間轉換為Unix TimeStamp
    C# 獲取Unix 時間戳
    C# Unix時間戳轉換

jash.liao@qq.com 發表迴響 取消回覆

你的電子郵件位址並不會被公開。 必要欄位標記為 *