ASP.net c# Parse int as datetime - c#

Given a time:
1286294501433
Which represents milliseconds passed since 1970, how do we convert this to a DateTime data type? EG:
transactionTime = "1286294501433";
UInt64 intTransTime = UInt64.Parse(transactionTime);
DateTime transactionActualDate = DateTime.Parse(intTransTime.ToString());
Throws:
String was not recognized as a valid
DateTime.
Please note all times passed into this function are guaranteed to be after 1970.

var dt = new DateTime(1970, 1, 1).AddMilliseconds(1286294501433);
You might also need to specify the DateTimeKind explicitly, depending on your exact requirements:
var dt = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
.AddMilliseconds(1286294501433);

And to simplify it even further and also take your local timezone into account:
Just create this integer number extension -
public static class currency_helpers {
public static DateTime UNIXTimeToDateTime(this int unix_time) {
return new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddSeconds(unix_time).ToLocalTime();
}
}
And then call it wherever like this:
var unix_time = 1336489253;
var date_time = unix_time.UNIXTimeToDateTime();
The value of date_time is:
5/8/2012 10:00:53 AM
(via: http://www.codeproject.com/Articles/10081/UNIX-timestamp-to-System-DateTime?msg=2494329#xx2494329xx)

Assuming this is unix time its the number of seconds, so
int unixtimestamp=int.Parse(str);
new DateTime(1970,1,1,0,0,0).AddSeconds(unixtimestamp);
like this fetcher guy said.
wiki says
Unix time, or POSIX time, is a system
for describing points in time, defined
as the number of seconds elapsed since
midnight proleptic Coordinated
Universal Time (UTC) of January 1,
1970, not counting leap seconds. I

Related

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);

Conversion to Unix timestamp is not working

I'm trying to convert DateTime to Unix timestamp.
static long ToUnixTime(DateTime dateTime)
{
var dateTimeOffset = new DateTimeOffset(dateTime);
return dateTimeOffset.ToUnixTimeSeconds();
}
But this function always return timestamp equal to something "Sun Jan 18 1970" instead of current DateTime. What is wrong with this?
The current date as expressed as a Unix timestamp is 1501093539, more or less.
I think you're checking yourself wrong; if I edit my code to add milliseconds, I get 1/18/1970. But unix times aren't in milliseconds. They're in seconds.
var dt = DateTime.Now;
var offset = new DateTimeOffset(dt);
var unix = offset.ToUnixTimeSeconds();
dt = new DateTime(1970,1,1,0,0,0);
dt = dt.AddSeconds(unix);
Debug.WriteLine(dt); // gives current date back
Change it to AddSeconds and you'll get the current date. Change it to AddMilliseconds and you'll get January 18th, 1970. Your code is actually fine.
Here is some code that will give you Unix time stamp with any version of the framework
public static class UnixDateTime
{
private static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
public static long GetUnixTimestamp(this DateTime input)
{
return (long)(input - UnixEpoch).TotalSeconds;
}
}
Then just use the extension method
var unixTimeStamp = DateTime.Now.GetUnixTimestamp();

Why my random DateTime generator make dates outside of range?

I have a function to generate random DateTime in range between two dates... and somehow it makes random dates that comes before minimal date. What's wrong with my code?
public void TestFunct()
{
GenerateRandomTimeBetweenDates(new Random(), DateTime.ParseExact("01.01.2017 00:00:00", "dd.MM.yyyy HH:mm:ss", CultureInfo.InvariantCulture), DateTime.ParseExact("01.02.2017 00:00:00", "dd.MM.yyyy HH:mm:ss", CultureInfo.InvariantCulture));
}
public DateTime GenerateRandomTimeBetweenDates(Random RNG, DateTime dt1, DateTime dt2)
{
int dt1_sec = (int)dt1.ToUniversalTime().Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds; //calc seconds since Unix epoch
int dt2_sec = (int)dt2.ToUniversalTime().Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;
int random_sec = RNG.Next(Math.Min(dt1_sec, dt2_sec), Math.Max(dt1_sec, dt2_sec)); //RNG is Random instance. Here I generate seconds amount between two amounts - minimal and maximal.
DateTime random_dt = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(random_sec); //I try to recreate date by adding generated seconds amount to Unix epoch.
if (random_dt.Year == 2016)
random_dt = random_dt; //this I use to trigger breakpoint
return random_dt;
}
The problem here is ToUniversalTime(). If your dates have kind of Local or Unspecified - ToUniversalTime will convert them to UTC assuming (in case of Unspecified) that they are local. By doing that, your dt1, which is January 1, 2017 will be represented in UTC as a date in 2016 year. When random value is close to minimal value - result will also be in 2016 year. To fix - just remove call to ToUniversalTime(). You can just remove it, because, by documentation of Substract method:
The System.DateTime.Subtract(System.DateTime) method does not
consider the value of the System.DateTime.Kind property of the two
System.DateTime values when performing the subtraction
Note however that it's better to return result with the same kind as inputs, so:
DateTime random_dt = new DateTime(1970, 1, 1, 0, 0, 0, dt1.Kind).AddSeconds(random_sec);
Because otherwise if your input represents local time and result is in UTC - doesn't make much sense.

long value to date c#

My server is sending me the following value 13928550480000 which I know represents the date 02/19/2014. But I am not able to figure out how to get to the date from the long value.
I tried various ways of converting long to date using c# date time class but not able to get to the correct date i.e. 02/19/2014
long dateL = 13928550480000;
DateTime dt = new DateTime(dateL);
var dtstr = dt.ToString("MM/dd/yyyy");
var onlyDate = dt.Date;
DateTime start = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
DateTime date = start.AddMilliseconds(dateL).ToLocalTime();
var dtstr1 = date.ToString("MM/dd/yyyy");
It looks like your source number represents number of 0.10 ms increments since 1-1-1970 (either that or a typo):
long dateL = 13928550480000;
DateTime start = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
DateTime date = start.AddMilliseconds(dateL/10).ToLocalTime();
// ***
// ^------
var dtstr1 = date.ToString("MM/dd/yyyy"); // 02/19/2014
I suspect the time zone difference is irrelevant to your problem.
Did you write too many zeros at the end of your big number? That is, does it really end in 0000 and not just 000?
If it really is 0000, then it appears to be measuring time in 100-microsecond increments (10,000 time increments per second). But it is probably also giving you time in GMT and you are expecting to derive local time from it. The time 1392855048 seconds from Jan. 1, 1970 would be 10 minutes 48 seconds past midnight on Feb. 20, 2014. Depending on your time zone, that could be sometime on Feb. 19 local time.

Trivia: How to convert a JSON2.org DateTime string to C# DateTime

Asp.Net MVC 2 Futures doesn't seem to handle JSON DateTime well (including double and decimal values). As such, I setup all inputs as string, used Data Validation, and things worked pretty well.
However, I have this JSON2.js date from Firefox 3.6:
"/Date(1288296203190)/"
How do I turn this in to a valid date in C#?
var a = new DateTime(1288296203190);
That doesn't give the right date (1/2/0001 11:47:09 AM) instead of Thu Oct 28 2010 16:03:23 GMT-0400 (Eastern Daylight Time). It's probably because a 32 bit integer is only 10 digits. However, this fails too:
var a = Int64.Parse("1288296203190");
var b = new DateTime(a);
b's value is 1/2/0001 11:47:09 AM.
What did it do? Wrap? Is this some kind of time travel "signed bit" issue?
The issue is the difference in epoch. Looks like the JSON2.js date you have uses the unix epoch (January 1, 1970) measured in ms. From the System.DateTime(long ticks) documenttion:
expects A date and time expressed in the number of 100-nanosecond intervals that have elapsed since January 1, 0001 at 00:00:00.000 in the Gregorian calendar.
Something like this should get you what you want.
var unixEpoch = DateTime(1970, 1, 1);
var ticksSinceEpoch = 1288296203190 * 10000;
var time = new DateTime(unixEpoch.Ticks + ticksSinceEpoch);
And there is even better way (which also takes your local timezone into account):
Just create this integer number extension -
public static class currency_helpers {
public static DateTime UNIXTimeToDateTime(this int unix_time) {
return new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddSeconds(unix_time).ToLocalTime();
}
}
And then call it wherever like this:
var unix_time = 1336489253;
var date_time = unix_time.UNIXTimeToDateTime();
The value of date_time is:
5/8/2012 10:00:53 AM
(via: http://www.codeproject.com/Articles/10081/UNIX-timestamp-to-System-DateTime?msg=2494329#xx2494329xx)
var jsonDate = "/Date(1288296203190+0530)/";
var strSec = jsonDate.Substring(6, 13);
var strTimeZone = jsonDate.Substring(19, 5);
sec = double.Parse(strSec);
var timeZoneHr = double.Parse(strTimeZone);
var timeZoneMin = timeZoneHr % 100;
timeZoneHr = Math.Ceiling(timeZoneHr / 100);
var date = new System.DateTime(1970, 1, 1, 0, 0, 0, 0)
.AddMilliseconds(sec)
.AddHours(timeZoneHr)
.AddMinutes(timeZoneMin);
I parsed the string myself. Its working fine for me. Anybody have other optimized way, please let me know.
This question is basically the same as this one: ASP.net c# Parse int as datetime.
And I think the accepted answer there is better than #matheeeny's answer (although matheeeny explained well the problem of OP's original solution).
I'll copy here LukeH's accepted answer:
var dt = new DateTime(1970, 1, 1).AddMilliseconds(1286294501433);
You might also need to specify the DateTimeKind explicitly, depending on your exact requirements:
var dt = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
.AddMilliseconds(1286294501433);

Categories