5

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.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Sreejith Sree
  • 3,055
  • 4
  • 36
  • 105

3 Answers3

9

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.

Sreejith Sree
  • 3,055
  • 4
  • 36
  • 105
Paul Kertscher
  • 9,416
  • 5
  • 32
  • 57
3

Try this :

10 digits:

public static long ConvertToTS(DateTime datetime)
{
    DateTime sTime = new DateTime(1970, 1, 1,0,0,0,DateTimeKind.Utc);

    return (long)(datetime - sTime).TotalSeconds;
}

13 digits:

public static long ConvertToTS(DateTime datetime)
{
    DateTime sTime = new DateTime(1970, 1, 1,0,0,0,DateTimeKind.Utc);

    return (long)(datetime - sTime).TotalMilliseconds;
}
Gaurang Dave
  • 3,956
  • 2
  • 15
  • 34
1
Int32 unixTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;

How to get the unix timestamp in C#

Gavin Stevens
  • 673
  • 5
  • 14