0

I come to you again becase i searched all stack and after found some similar topics anyway no one was working in my case. I ask you to support me in one thing. I have this code:

static class UnixTime {
    private static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
    private static readonly long MaxUnixSeconds = (long)((DateTime.MaxValue - UnixEpoch).TotalSeconds);
    private const double LongAdj = 1000.0;
    public static DateTime ToDateTime(long unixTimeStamp) { return UnixEpoch.AddSeconds(unixTimeStamp / LongAdj); }
    public static long FromDateTime(DateTime date) { return (long)((date - UnixEpoch).TotalSeconds * LongAdj); }

    public static void Test(long n) {
        System.Diagnostics.Debug.WriteLine("UNIX Time = " + n);
        var dt = ToDateTime(n);
        System.Diagnostics.Debug.WriteLine("DateTime = " + dt);
        var fromDt = FromDateTime(dt);
        System.Diagnostics.Debug.WriteLine("UNIX Time = " + fromDt);
        System.Diagnostics.Debug.WriteLine("IsGood = " + (n==fromDt));
    }

    public static void Test() { Test(1300123800440); }
}

The output of it is:

UNIX Time = 1300123800440
DateTime = 3/14/2011 5:30:00 PM
UNIX Time = 1300123800440
IsGood = True

its working really fine. Anyway i extracted from above code the one i need to pass datetime as parameter and get Unix timestamp unfortunetly it giving me bad results:

I did like this:

public static long ConvertDateTimeTo(string date)
        {
            const double LongAdj = 1000.0;
            DateTime mydate = Convert.ToDateTime(date);
            DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            return (long)((mydate - UnixEpoch).TotalSeconds * LongAdj);
        }

use:

Console.WriteLine(ConvertDateTimeTo("14.03.2011 5:30 PM"));

output (should be 1300123800440) but i am receiving:

1300123800000

could you help me out what is wrong here?

Rashmin Javiya
  • 5,173
  • 3
  • 27
  • 49
Notification
  • 13
  • 1
  • 1
  • 7
  • What is the time zone of the input expected to be? (And can you change the format?) – Jon Skeet Sep 02 '14 at 08:22
  • http://stackoverflow.com/questions/17632584/how-to-get-the-unix-timestamp-in-c-sharp – fubo Sep 02 '14 at 08:24
  • Where are you getting the 440ms from? – Jesper Fyhr Knudsen Sep 02 '14 at 08:24
  • Jon: UTC. | UNIX Time 1300123800440 is equal to 3/14/2011 5:30:00 PM – Notification Sep 02 '14 at 08:43
  • @Notification That is not UNIX time, UNIX time is seconds passed, not ms, ie 1 billion something something (1 billion seconds is roughly 31 years). – flindeberg Sep 02 '14 at 08:49
  • @JonSkeet Do you know of any 440 ms timezones? Is it per chance relativistic? :) (would have been really really cool though) – flindeberg Sep 02 '14 at 08:50
  • So why in db i got values like that: 1300123800440 which i convert to datetime using UnixTime class i showed you and its equal to 14.03.2011 5:30 PM. For this one: 1300124700345 i retreived: 14.03.2011 5:45 PM. But gouing back with my next method i am not retreiving same. What should i do in this case? – Notification Sep 02 '14 at 09:13
  • @Notification You are not using UNIX-time, please use another word, like NOTIFICATION-time or something, and your date strings are not showing milliseconds! You do NOT have a 1-1 mapping. – flindeberg Sep 02 '14 at 09:21
  • @flindeberg: Nope, hadn't spotted that the difference was that small - well spotted. – Jon Skeet Sep 02 '14 at 09:27
  • 1300123800000 DateTime = 2011-03-14 17:30:00 and 1300123800440 DateTime = 2011-03-14 17:30:00. The same datetime for diffrent timestamp. So i should not carry about that and trade my method as good enough? I am asking because i would request unix server and need to put timestamps inside it that why i need converting datetime to timestamps – Notification Sep 02 '14 at 09:37
  • Downvoted for taking somebody else's code and then claiming it as his own. (Code from http://www.dreamincode.net/forums/topic/352912-convert-from-datetime-to-unix-time/page__view__findpost__p__2046757 ) – Ants Sep 03 '14 at 02:52
  • Possible duplicate of [How to convert a Unix timestamp to DateTime and vice versa?](https://stackoverflow.com/questions/249760/how-to-convert-a-unix-timestamp-to-datetime-and-vice-versa) – BobbyA Dec 13 '17 at 15:29

3 Answers3

5

You could try this

static void Main(string[] args)
        {
            Console.WriteLine(DateTime.Now);
            Console.ReadLine();
        }

        public static long ToUnixTimestamp( DateTime target)
        {
            var date = new DateTime(1970, 1, 1, 0, 0, 0, target.Kind);
            var unixTimestamp = System.Convert.ToInt64((target - date).TotalSeconds);

            return unixTimestamp;
        }

        public static DateTime ToDateTime( DateTime target, long timestamp)
        {
            var dateTime = new DateTime(1970, 1, 1, 0, 0, 0, target.Kind);

            return dateTime.AddSeconds(timestamp);
        }

EDIT

This works for me

Found it on here: http://hassakarn.com/2012/10/10/convert-datetime-to-unix-timestamp-in-c/

  • If i use this solution like this: DateTime mydate = Convert.ToDateTime("14.03.2011 5:30 PM"); Console.WriteLine(ToUnixTimestamp(DateTime.Now)); I am retreiving: 1409655937 but should be 14.03.2011 5:30 PM – Notification Sep 02 '14 at 09:06
  • When working with JavaScript Date, you have to multiply (or divide) the seconds by 1000. – cskwg Sep 14 '20 at 14:15
1

Convert the UTC Datetime to Unix/GMT/UTC timestamp in milliseconds try the below function.

public static long getUTCTimeInMilliseconds(DateTime utcDT)
        {
            DateTime convertedDate = DateTime.SpecifyKind(utcDT, DateTimeKind.Utc);
            return new DateTimeOffset(convertedDate).ToUnixTimeMilliseconds();
        }
Ravindra Vairagi
  • 1,055
  • 15
  • 22
0

Have a look at this instead:

public static void Test() { Test(13001238000000); }

Gives:

Debug Trace: 
UNIX Time = 1300123800000 
DateTime = 2011-03-14 17:30:00
UNIX Time = 1300123800000 
IsGood = True

Your difference is way too small man, its 440 ms, and you are not doing Unix-time. Unix-time is seconds passed, not milliseconds passed since 1970-01-01.

To clarify, the reason you are getting the same "date string" is because you are only showing seconds in your date string, not milliseconds.

flindeberg
  • 4,887
  • 1
  • 24
  • 37
  • hmm but if look on examples i have e.g: 1300123800440 = 14.03.2011 5:30 PM 1300124700345 = 14.03.2011 5:45 PM – Notification Sep 02 '14 at 08:58
  • @Notification 1300123800000 = 14.03.2011 5:30 PM, 1300123800440 = 14.03.2011 5:30 PM + 440 ms – flindeberg Sep 02 '14 at 09:18
  • i got it now. So now the main question if i want to pass two datetimes which should be converted to unix time and pass towards unix server. Two datetimes e.g : >= 14.03.2011 00:00:00 AM and < 15.03.2011 00:00:00 AM then i could just use my method ConvertDateTimeTo and get correct timestamps? So: ConvertDateTimeTo("14.03.2011 00:00:00 AM"); ConvertDateTimeTo("15.03.2011 00:00:00 AM"); will be ok after i send it to unix? – Notification Sep 02 '14 at 10:09
  • You are not using UNIX-time though, your values are 1000 times too big, a magnitude of 3 wrong. 1 300 123 800 is the correct timestamp, not 1 300 123 800 000, so if you are sending unix-time you are sending the wrong values. 1 300 123 800 000 is 41 000 years, ie year 42 971, which I guess is not what you want. – flindeberg Sep 02 '14 at 11:29
  • so why on unix i got it in this format: 1300123800440. From your answer 3 last digits should not be there but there are. Anyway after conversion i can just cut last 3 digits off and will be ok? – Notification Sep 02 '14 at 11:52
  • Where do you get the original timestamps from? – flindeberg Sep 02 '14 at 11:55
  • from the unix oracle database there is field timeCaptured and the numbers like i wrote. By the way if i want to pass values like from midnight to midnight i can convert like i am doing now - the miliseconds will not overload my time because still the seconds are ok. – Notification Sep 02 '14 at 12:32