forked from csainty/ServiceStack.Text
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDateTimeExtensions.cs
More file actions
71 lines (60 loc) · 2.08 KB
/
Copy pathDateTimeExtensions.cs
File metadata and controls
71 lines (60 loc) · 2.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
//
// http://code.google.com/p/servicestack/wiki/TypeSerializer
// ServiceStack.Text: .NET C# POCO Type Text Serializer.
//
// Authors:
// Demis Bellot (demis.bellot@gmail.com)
//
// Copyright 2011 Liquidbit Ltd.
//
// Licensed under the same terms of ServiceStack: new BSD license.
//
using System;
using ServiceStack.Text.Common;
namespace ServiceStack.Text
{
/// <summary>
/// A fast, standards-based, serialization-issue free DateTime serailizer.
/// </summary>
public static class DateTimeExtensions
{
public const long UnixEpoch = 621355968000000000L;
private static readonly DateTime UnixEpochDateTime = new DateTime(UnixEpoch);
public const long TicksPerMs = TimeSpan.TicksPerSecond / 1000;
public static long ToUnixTime(this DateTime dateTime)
{
var epoch = (dateTime.ToUniversalTime().Ticks - UnixEpoch) / TimeSpan.TicksPerSecond;
return epoch;
}
public static DateTime FromUnixTime(this double unixTime)
{
return UnixEpochDateTime + TimeSpan.FromSeconds(unixTime);
}
public static long ToUnixTimeMs(this DateTime dateTime)
{
var epoch = (dateTime.ToUniversalTime().Ticks - UnixEpoch) / TicksPerMs;
return epoch;
}
public static DateTime FromUnixTimeMs(this double msSince1970)
{
var ticks = (long)(UnixEpoch + (msSince1970 * TicksPerMs));
return new DateTime(ticks, DateTimeKind.Utc).ToLocalTime();
}
public static DateTime RoundToSecond(this DateTime dateTime)
{
return new DateTime(((dateTime.Ticks) / TimeSpan.TicksPerSecond) * TimeSpan.TicksPerSecond);
}
public static string ToShortestXsdDateTimeString(this DateTime dateTime)
{
return DateTimeSerializer.ToShortestXsdDateTimeString(dateTime);
}
public static DateTime FromShortestXsdDateTimeString(this string xsdDateTime)
{
return DateTimeSerializer.ParseShortestXsdDateTime(xsdDateTime);
}
public static bool IsEqualToTheSecond(this DateTime dateTime, DateTime otherDateTime)
{
return dateTime.ToUniversalTime().RoundToSecond().Equals(otherDateTime.ToUniversalTime().RoundToSecond());
}
}
}