Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert current date and time into timestamp object (13 digits) [duplicate]

Tags:

c#

The following is the code for converting java datestamp (13digits) to date (1520488577604 to 3/12/2018 8:07:02 PM) in C#.

new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
    .AddMilliseconds((long)value) // put your value here
    .ToLocalTime().ToString("g");

I need to reverse this feature, need to convert from 3/12/2018 8:07:02 PM to 1520488577604.

like image 393
Sreejith Sree Avatar asked Mar 13 '18 05:03

Sreejith Sree


1 Answers

Though Gavin and Gaurang are pretty close, they missed a detail: You wanted the total milliseconds from 1970/01/01

namespace MyApp.Extensions
{
    public static class DateTimeExtensions
    {
        public static long MillisecondsTimestamp(this DateTime date)
        {
            DateTime baseDate = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            return (long)(date.ToUniversalTime()-baseDate).TotalMilliseconds;
        }
    }
}

You can use it like

using MyApp.Extensions;

// ...
var millisecondsTimestamp = DateTime.Now.MillisecondsTimestamp();

given that you've added the namespace the DateTimeExtensions is located in.

like image 93
Paul Kertscher Avatar answered Oct 03 '22 00:10

Paul Kertscher