Convert epoch/unix to Datetime [duplicate] - c#

This question already has answers here:
How do you convert epoch time in C#?
(14 answers)
Closed 9 years ago.
This is question is not a duplicate, this quesitons demonstrates a problem with a method of conversion, not how to perform the conversion. Read the question in full.
I have a timestamp which I believe is a unix time stamp, when using the following converter it correctly converts the stamp
Value: 1365151714493
http://www.epochconverter.com/
I have looked around and found an example on how to convert this to a datetime obect and the method seems simple, create a datetime object and set the date to the might night on 1/1/1970 and add the value as second:
public static DateTime? ConvertUnixTimeStamp(string unixTimeStamp)
{
return new DateTime(1970, 1, 1, 0, 0).AddSeconds(Convert.ToDouble(unixTimeStamp));
}
The problem is everytime I call this mehod with the value above I get a value out of range exception.
Do I need to do anything with the value first? the string converts to a double ok. the exception is thrown when calling the AddSeconds(double) methos

That timestamp (1365151714493) is in milliseconds, not seconds. You'll need to divide by 1000 or use AddMilliseconds instead. If it's treated as seconds, it's a date some 43,259 (rough calculation) years in the future. This is beyond the range of DateTime which maxes out at the year 10000, thus throwing the ArgumentOutOfRangeException.
public static DateTime? ConvertUnixTimeStamp(string unixTimeStamp)
{
return new DateTime(1970, 1, 1, 0, 0, 0).AddMilliseconds(Convert.ToDouble(unixTimeStamp));
}
You may also want to consider forcing it to GMT as V4Vendetta suggested. In addition, if you expect to have a mix of formats (seconds OR milliseconds) perhaps a quick size check on the parsed value might be prudent.

I guess you should try it as since it is with respect to GMT
Also from the site you mention it assumes that the value is in milliseconds and not the traditional unix timestamp as in seconds
DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
epoch = epoch.AddMilliseconds(yourvalue);// your case results to 4/5/2013 8:48:34 AM

Related

how convert 1606813200000 to 2020-12-01T09:00:00.000Z with c# [duplicate]

This question already has answers here:
How can I convert a Unix timestamp to DateTime and vice versa?
(21 answers)
Given a DateTime object, how do I get an ISO 8601 date in string format?
(18 answers)
Closed 1 year ago.
can not convert date The following object to datetime in c#
{"date":1606813200000 , "open":119000.0, "high":130900.0, "low":107500.0, "close":113300.0, "volume":36892044.0}
I do not understand the relationship between the two
Why 1606813200000 == 2020-12-01T09:00:00.000Z?
can you cee , ralationship to site https://jsoneditoronline.org/
The number you see is a Javascript timestamp (number of milliseconds elapsed since January 1, 1970 00:00:00 UTC). You can test it in any browser console:
Following this article, you can convert back to DateTime object:
public static DateTime ConvertFromUnixTimestamp(double timestamp)
{
DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
return origin.AddSeconds(timestamp / 1000); // convert from milliseconds to seconds
}
From the comment, I realize there is this method DateTimeOffset.FromUnixTimeMilliseconds as well:
// Convert Timestampt to DateTimeOffset
var time = DateTimeOffset.FromUnixTimeMilliseconds(1606813200000);
// Convert back to ISO string
var isoString = time.ToString("o");

How can I convert the number of seconds since Jan 1st 1970 into a datetime value?

I have a number that is the number of seconds since January 1st 1970. It was created with this:
var utcNow = (int) Math.Truncate(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds);
Now need to convert that number to a date in string form like this:
Tue, Jan 15, 2019
Can someone give me some suggestions on how I can do this. I think I can format it myself but I need a suggestion on how to convert the integer utcNow into a datetime first.
static readonly DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
...
DateTime time = epoch.AddSeconds(utcNow);
You can also use this in reverse:
var seconds = (time - epoch).TotalSeconds;
(which gives a double, but you can cast it to int or long etc)
Some answer are already given, and work. But this is, I believe, the most elegant way of doing it. I'm using DateTimeOffset.FromUnixTimeSeconds(int64)
DateTimeOffset dt = DateTimeOffset.FromUnixTimeSeconds(utcNow);
And now you can convert it into a DateTime Struct with help of this blog entry
Substract the given time from current time and it gives timespan instance, from that you can get total seconds
var fromDate = new DateTime(1970,1 ,1);
var diffrance = DateTime.UtcNow.Subtract(fromDate);
Console.WriteLine(diffrance.TotalSeconds);

GroupWise 2014 Date Format to DateTime

I'm working with the GroupWise 2014 Rest API and I have a problem parsing their date format.
When you fetch a user you receive a json object with "timeCreated": 1419951016000,
But I can't figure out what format that date is.
I've tried
DateTime.Parse
DateTime.FromFileTime
DateTime.FromFileTimeUtc
The value 1419951016000 should be around the time 2014-12-30 15:50
Looks like unix time in milliseconds since January 1st, 1970 at UTC. Current unix time in seconds is shown here as 1419964283.
To convert to a DateTime to unix time, see here: How to convert UNIX timestamp to DateTime and vice versa?. That code works for unix time in seconds; the following works for unix time in milliseconds, represented as a long:
public static class UnixTimeHelper
{
const long MillisecondsToTicks = 10000;
static readonly DateTime utcEpochStart = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
static DateTime UtcEpochStart { get { return utcEpochStart; }}
public static DateTime ToDateTime(long unixTimeInMs, DateTimeKind kind)
{
var dateTime = UtcEpochStart + new TimeSpan(MillisecondsToTicks * unixTimeInMs);
if (kind == DateTimeKind.Local)
dateTime = dateTime.ToLocalTime();
return dateTime;
}
public static long ToUnixTimeInMs(DateTime dateTime)
{
if (dateTime.Kind == DateTimeKind.Local)
dateTime = dateTime.ToUniversalTime();
var span = dateTime - UtcEpochStart;
return (long)(span.Ticks / MillisecondsToTicks);
}
}
With this code. UnixTimeHelper.ToDateTime(1419951016000, DateTimeKind.Utc).ToString() gives the value "12/30/2014 2:50:16 PM". Is your desired value of "2014-12-30 15:50" in UTC or your local time?
If you are using Json.NET to serialize your JSON, you can write a custom JsonConverter to do the conversion automatically from a DateTime property using the instructions here: Writing a custom Json.NET DateTime Converter . That code also works for unix time in seconds and so will need to be tweaked.
(Finally, seconding Plutonix's suggestion to double-check the documentation. In particular you need to read what the documentation says about the time zone in which the times are returned. It's probably UTC but it pays to make sure.)
Update
After a quick search the online doc looks pretty bad, but this page makes mention of
expiretime
long
Optional. Use an explicit expiration cut-off time. The time is specified as a java long time.
java.util.Date represents "the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT" as a long.

TimeSpan to DateTime conversion

I want to convert a Timespan to Datetime. How can I do this?
I found one method on Google:
DateTime dt;
TimeSpan ts="XXX";
//We can covnert 'ts' to 'dt' like this:
dt= Convert.ToDateTime(ts.ToString());
Is there any other way to do this?
It is not very logical to convert TimeSpan to DateTime. Try to understand what leppie said above. TimeSpan is a duration say 6 Days 5 Hours 40 minutes. It is not a Date. If I say 6 Days; Can you deduce a Date from it? The answer is NO unless you have a REFERENCE Date.
So if you want to convert TimeSpan to DateTime you need a reference date. 6 Days & 5 Hours from when? So you can write something like this:
DateTime dt = new DateTime(2012, 01, 01);
TimeSpan ts = new TimeSpan(1, 0, 0, 0, 0);
dt = dt + ts;
While the selected answer is strictly correct, I believe I understand what the OP is trying to get at here as I had a similar issue.
I had a TimeSpan which I wished to display in a grid control (as just hh:mm) but the grid didn't appear to understand TimeSpan, only DateTime . The OP has a similar scenario where only the TimeSpan is the relevant part but didn't consider the necessity of adding the DateTime reference point.
So, as indicated above, I simply added DateTime.MinValue (though any date will do) which is subsequently ignored by the grid when it renders the timespan as a time portion of the resulting date.
TimeSpan can be added to a fresh DateTime to achieve this.
TimeSpan ts="XXX";
DateTime dt = new DateTime() + ts;
But as mentioned before, it is not strictly logical without a valid start date. I have encountered
a use-case where i required only the time aspect. will work fine as long as the logic is correct.
You need a reference date for this to be useful.
An example from
http://msdn.microsoft.com/en-us/library/system.datetime.add.aspx
// Calculate what day of the week is 36 days from this instant.
System.DateTime today = System.DateTime.Now;
System.TimeSpan duration = new System.TimeSpan(36, 0, 0, 0);
System.DateTime answer = today.Add(duration);
System.Console.WriteLine("{0:dddd}", answer);
Worked for me.
var StartTime = new DateTime(item.StartTime.Ticks);
If you only need to show time value in a datagrid or label similar, best way is convert directly time in datetime datatype.
SELECT CONVERT(datetime,myTimeField) as myTimeField FROM Table1
You could also use DateTime.FromFileTime(finishTime) where finishTme is a long containing the ticks of a time. Or FromFileTimeUtc.
An easy method, use ticks:
new DateTime((DateTime.Now - DateTime.Now.AddHours(-1.55)).Ticks).ToString("HH:mm:ss:fff")
This function will give you a date (Without Day / Month / Year)
A problem with all of the above is that the conversion returns the incorrect number of days as specified in the TimeSpan.
Using the above, the below returns 3 and not 2.
Ideas on how to preserve the 2 days in the TimeSpan arguments and return them as the DateTime day?
public void should_return_totaldays()
{
_ts = new TimeSpan(2, 1, 30, 10);
var format = "dd";
var returnedVal = _ts.ToString(format);
Assert.That(returnedVal, Is.EqualTo("2")); //returns 3 not 2
}
First, convert the timespan to a string, then to DateTime, then back to a string:
Convert.ToDateTime(timespan.SelectedTime.ToString()).ToShortTimeString();

Adding Seconds to DateTime with a Valid Double Results in ArgumentOutOfRangeException

The following code crashes and burns and I don't understand why:
DateTime dt = new DateTime(1970,1,1,0,0,0,0, DateTimeKind.Utc);
double d = double.Parse("1332958778172");
Console.Write(dt.AddSeconds(d));
Can someone tell me what's going on? I just can't seem to be able to figure out why...
EDIT
This value comes back from the Salesforce REST API and from what I understand it's a Unix epoch time stamp. "The time of token issue, represented as the number of seconds since the Unix epoch (00:00:00 UTC on 1 January 1970)."
SOLUTION
Salesforce REST API is in fact sending milliseconds back for the issued_at field when performing the OAuth request when they say they're sending seconds...
As others have said, the problem is that the value is too large.
Having looked over it, I believe it represents milliseconds since the Unix epoch, not seconds so you want:
DateTime dt = new DateTime(1970,1,1,0,0,0,0, DateTimeKind.Utc);
double d = double.Parse("1332958778172"); // Or avoid parsing if possible :)
Console.Write(dt.AddMilliseconds(d));
Either that, or divide by 1000 before calling AddSeconds - but obviously that will lose data.
The value you are adding results in a date outside of the valid range of dates that a DateTime supports.
DateTime supports 01/01/0001 00:00:00 to 31/12/9999 23:59:59.
A simple calculation of 1332958778172/3600/24/365 gives 42267 years.
I think the double value is genuinely too large. It represents just over 42,267 years (if my maths is correct), and DateTime.MaxValue is 23:59:59.9999999, December 31, 9999
DateTime dt = new DateTime(1970,1,1,0,0,0,0, DateTimeKind.Utc);
Console.Write(dt.AddSeconds(1332958778172D));
Except that...
1332958778172/60/60/24/365 = 42,267 years... which DateTime can only go up to 23:59:59.9999999, December 31, 9999
I had a similar issue where I was required to add a configurable timespan to a datetime.
If the configuration is not correct I have to assume the 'worst scenario' : MaxValue.
I solved it by implementing an extension to DateTime (still in test phase) :
/// <summary>
/// Removes a timespan from a date, returning MinValue or MaxValue instead of throwing exception when if the resulting date
/// is behind the Min/Max values
/// </summary>
/// <returns></returns>
public static DateTime SafeAdd(this DateTime source, TimeSpan value)
{
// Add or remove ?
if (value.Ticks > 0)
{
// add
var maxTicksToAdd = DateTime.MaxValue - source;
if (value.Ticks > maxTicksToAdd.Ticks)
return DateTime.MaxValue;
}
else
{
var maxTicksToRemove = source - DateTime.MinValue;
// get the value to remove in unsigned representation.
// negating MinValues is impossible because it would result in a value bigger than MaxValue : (-32768 .. 0 .. 32767)
var absValue = value == TimeSpan.MinValue ? TimeSpan.MaxValue : -value;
if (absValue.Ticks > maxTicksToRemove.Ticks)
return DateTime.MinValue;
}
return source + value;
}
Looks like this timestamp is in milliseconds, try below code it should work fine.
DateTime nDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
double epoch = 1585008000000;
DateTime rDate = nDateTime.AddMilliseconds(epoch);
In my case I had to consume an api object as a double and convert the unix time to a DateTime:
DateTime Date = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(Double.Parse("1596225600000"));

Categories