Last active
May 28, 2018 09:56
-
-
Save matarillo/5794336 to your computer and use it in GitHub Desktop.
C# におけるDateTime型/TimeStamp型の変換方法のまとめ @ Gist
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
「誰もが一度は陥る日付処理。各種プログラミング言語におけるDateTime型/TimeStamp型の変換方法のまとめ」 | |
(http://d.hatena.ne.jp/yutakikuchi/20130617/1371425713) のC# 版。 | |
Web系言語にJavaが入るんだったらC#だって入るかもね。 | |
なお、Unix Epochはもっと短いコードで得ることもできるだろうけど、今回は長めに書きました。 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
class Program | |
{ | |
static void Main() | |
{ | |
// 1: 文字列のローカル日付を取得 | |
var localDate1 = DateTime.Now; | |
Console.WriteLine(localDate1.ToString("yyyy-MM-dd HH:mm:ss")); | |
// 2: Unix Timestamp 取得 | |
// .NETのDateTimeは0001/1/1基点なので、変換が必要。 | |
var timespan2 = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); | |
Console.WriteLine((uint)timespan2.TotalSeconds); | |
// 3: 文字列のローカル日付をUnix Timestampに変換 | |
// Parseメソッドはお任せ動作。フォーマットを指定しなくていい。 | |
var localDate3 = "2013-06-15 12:00:00"; | |
var timespan3 = DateTime.Parse(localDate3).ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); | |
Console.WriteLine((uint)timespan3.TotalSeconds); | |
// 4: Unix Timestampをローカル日付に変換 | |
var timestamp4 = 1371265200u; | |
var localDate4 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(timestamp4).ToLocalTime(); | |
Console.WriteLine(localDate4.ToString("yyyy-MM-dd HH:mm:ss")); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment