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();
Related
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);
Well I am trying to convert System's current date and time into integer value and then adding it into List.
The code is
List<int> _data = new List<int>();
foreach (DataRow row in dt.Rows)
{
_data.Add((int)Convert.ToInt32(DateTime.Now.ToLocalTime()));
_data.Add((int)Convert.ToInt32(row["S11"]));
}
JavaScriptSerializer jss = new JavaScriptSerializer();
chartData = jss.Serialize(_data);
Response.Write(chartData);
I am getting error which says Invalid cast from "DateTime' to 'Int32'
I want to convert in such form to make the json which look like[1386216561000,74] Here the first member is time in integer format and second is the data which is coming from sql server.
Actually what I am trying to do is something similar to this php code.
The code is
<?php
// Set the JSON header
header("Content-type: text/json");
$x = time() * 1000;
// The y value is a random number
$y = rand(0, 100);
// Create a PHP array and echo it as JSON
$ret = array($x, $y);
echo json_encode($ret);
?>
You need to convert your time to Epoch time or to some timespan value from a certain reference point.
Here is the code how you calculate a epoch time:
var timeDiff=DateTime.UtcNow - new DateTime(1970, 1, 1);
var totaltime = timeDiff.TotalMilliseconds;
The PHP time() function returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).
So to mimic this functionality in C#, try this:
private static double GetUnixEpoch(this DateTime dateTime)
{
var unixTime = dateTime.ToUniversalTime() -
new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return unixTime.TotalSeconds;
}
Usage:
var unixTime1 = DateTime.Now.GetUnixEpoch();
Note: GetUnixEpoch returns a double.
So your code should read like this:
List<double> _data = new List<double>();
foreach (DataRow row in dt.Rows)
{
_data.Add(DateTime.Now.GetUnixEpoch());
_data.Add((double)Convert.ToDouble(row["S11"]));
}
JavaScriptSerializer jss = new JavaScriptSerializer();
chartData = jss.Serialize(_data);
Response.Write(chartData);
DateTime cannot be implicitly converted to int. Consider using ToString() with format. For example...
_data.Add((int)Convert.ToInt32(DateTime.Now.ToLocalTime().ToString("HHmmssfff"));
Good Luck!
You can convert your date into UnixTime Stamp :
Convert Date Into UnixTimeStamp :
public static double DateTimeToUnixTimestamp(DateTime dateTime)
{
return (dateTime - new DateTime(1970, 1, 1).ToLocalTime()).TotalSeconds;
}
Converta UnitTimeStamp to Date :
public static DateTime UnixTimeStampToDateTime( double unixTimeStamp )
{
// Unix timestamp is seconds past epoch
System.DateTime dtDateTime = new DateTime(1970,1,1,0,0,0,0);
dtDateTime = dtDateTime.AddSeconds( unixTimeStamp ).ToLocalTime();
return dtDateTime;
}
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
Console.WriteLine ( Convert.ToInt64((DateTime.UtcNow - epoch).TotalSeconds));;
Epoch time starts on 1 Jan 1970, we get the current UTC time and subtract the date Epoch time starts from, we then convert the value to the total number of seconds that has passed since Epoch time.
Additionally, we convert the value to Int64, as Int32 will no longer be able to store the total number of seconds once we reach 2038.
How do I convert datetime to timestamp using C# .NET (ignoring the current timezone)?
I am using the below code:
private long ConvertToTimestamp(DateTime value)
{
long epoch = (value.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
return epoch;
}
But it returns the timestamp value according to the current time zone & and I need the result without using the current timezone.
At the moment you're calling ToUniversalTime() - just get rid of that:
private long ConvertToTimestamp(DateTime value)
{
long epoch = (value.Ticks - 621355968000000000) / 10000000;
return epoch;
}
Alternatively, and rather more readably IMO:
private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
...
private static long ConvertToTimestamp(DateTime value)
{
TimeSpan elapsedTime = value - Epoch;
return (long) elapsedTime.TotalSeconds;
}
EDIT: As noted in the comments, the Kind of the DateTime you pass in isn't taken into account when you perform subtraction. You should really pass in a value with a Kind of Utc for this to work. Unfortunately, DateTime is a bit broken in this respect - see my blog post (a rant about DateTime) for more details.
You might want to use my Noda Time date/time API instead which makes everything rather clearer, IMO.
I'm not exactly sure what it is that you want. Do you want a TimeStamp? Then you can do something simple like:
TimeStamp ts = TimeStamp.FromTicks(value.ToUniversalTime().Ticks);
Since you named a variable epoch, do you want the Unix time equivalent of your date?
DateTime unixStart = DateTime.SpecifyKind(new DateTime(1970, 1, 1), DateTimeKind.Utc);
long epoch = (long)Math.Floor((value.ToUniversalTime() - unixStart).TotalSeconds);
Find timestamp from DateTime:
private long ConvertToTimestamp(DateTime value)
{
TimeZoneInfo NYTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
DateTime NyTime = TimeZoneInfo.ConvertTime(value, NYTimeZone);
TimeZone localZone = TimeZone.CurrentTimeZone;
System.Globalization.DaylightTime dst = localZone.GetDaylightChanges(NyTime.Year);
NyTime = NyTime.AddHours(-1);
DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime();
TimeSpan span = (NyTime - epoch);
return (long)Convert.ToDouble(span.TotalSeconds);
}
JonSkeet has a good answer but as an alternative if you wanted to keep the result more portable you could convert the date into an ISO 8601 format which could then be read into most other frameworks but this may fall outside your requirements.
value.ToUniversalTime().ToString("O");
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
From another answer on Stackoverflow is a conversion from Javascript date to .net DateTime:
long msSinceEpoch = 1260402952906; // Value from Date.getTime() in JavaScript
return new DateTime(1970, 1, 1) + new TimeSpan(msSinceEpoch * 10000);
But how to do the reverse? DateTime to Javascript Date?
Try:
return DateTime.Now.Subtract(new DateTime(1970, 1,1)).TotalMilliseconds
Edit: true UTC is better, but then we need to be consistent
return DateTime.UtcNow
.Subtract(new DateTime(1970,1,1,0,0,0,DateTimeKind.Utc))
.TotalMilliseconds;
Although, on second thoughts it does not matter, as long as both dates are in the same time zone.
JavaScript Date constructor accepts number of milliseconds since Unix epoch (1 January 1970 00:00:00 UTC). Here’s C# extension method that converts .Net DateTime object to JavaScript date:
public static class DateTimeJavaScript
{
private static readonly long DatetimeMinTimeTicks =
(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).Ticks;
public static long ToJavaScriptMilliseconds(this DateTime dt)
{
return (long)((dt.ToUniversalTime().Ticks - DatetimeMinTimeTicks) / 10000);
}
}
JavaScript Usage:
var dt = new Date(<%= DateTime.Today.ToJavaScriptMilliseconds() %>);
alert(dt);
You can try this in your Action:
return DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss");
And this in your Ajax success:
success: function (resultDateString) {
var date = new Date(resultDateString);
}
Or this in your View: (Javascript plus C#)
var date = new Date('#DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss")');
With Moment.js simply use:
var jsDate = moment(netDateTime).toDate();
Where netDateTime is your DateTime variable serialized, something like "/Date(1456956000000+0200)/".
This should do the trick:
date.Subtract(new DateTime(1970, 1,1)).TotalMilliseconds
Another late answer, but this is missing here. If you want to handle conversion of serialized /Date(1425408717000)/ in javascript, you can simply call:
var cSharpDate = "/Date(1425408717000)/"
var jsDate = new Date(parseInt(cSharpDate.replace(/[^0-9 +]/g, '')));
Source: amirsahib
I know this is a little late, but here's the solution I had to come up with for handling dates when you want to be timezone independent. Essentially it involves converting everything to UTC.
From Javascript to Server:
Send out dates as epoch values with the timezone offset removed.
var d = new Date(2015,0,1) // Jan 1, 2015
// Ajax Request to server ...
$.ajax({
url: '/target',
params: { date: d.getTime() - (d.getTimezoneOffset() * 60 * 1000) }
});
The server then recieves 1420070400000 as the date epoch.
On the Server side, convert that epoch value to a datetime object:
DateTime d = new DateTime(1970, 1, 1, 0, 0, 0).AddMilliseconds(epoch);
At this point the date is just the date/time provided by the user as they provided it. Effectively it is UTC.
Going the other way:
When the server pulls data from the database, presumably in UTC, get the difference as an epoch (making sure that both date objects are either local or UTC):
long ms = (long)utcDate.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
or
long ms = (long)localDate.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Local)).TotalMilliseconds;
When javascript receives this value, create a new date object. However, this date object is going to be assumed local time, so you need to offset it by the current timezone:
var epochValue = 1420070400000 // value pulled from server.
var utcDateVal = new Date(epochValue);
var actualDate = new Date(utcDateVal.getTime() + (utcDateVal.getTimezoneOffset() * 60 * 1000))
console.log(utcDateVal); // Wed Dec 31 2014 19:00:00 GMT-0500 (Eastern Standard Time)
console.log(actualDate); // Thu Jan 01 2015 00:00:00 GMT-0500 (Eastern Standard Time)
As far as I know, this should work for any time zone where you need to display dates that are timezone independent.
This method is working for me:
public sCdateToJsDate(cSDate: any): Date {
// cSDate is '2017-01-24T14:14:55.807'
var datestr = cSDate.toString();
var dateAr = datestr.split('-');
var year = parseInt(dateAr[0]);
var month = parseInt(dateAr[1])-1;
var day = parseInt(dateAr[2].substring(0, dateAr[2].indexOf("T")));
var timestring = dateAr[2].substring(dateAr[2].indexOf("T") + 1);
var timeAr = timestring.split(":");
var hour = parseInt(timeAr[0]);
var min = parseInt(timeAr[1]);
var sek = parseInt(timeAr[2]);
var date = new Date(year, month, day, hour, min, sek, 0);
return date;
}
If you use MVC with razor
-----Razor/C#
var dt1 = DateTime.Now.AddDays(14).Date;
var dt2 = DateTime.Now.AddDays(18).Date;
var lstDateTime = new List<DateTime>();
lstDateTime.Add(dt1);
lstDateTime.Add(dt2);
---Javascript
$(function() {
var arr = []; //javascript array
#foreach (var item in lstDateTime)
{
#:arr1.push(new Date(#item.Year, #(item.Month - 1), #item.Day));
}
1: create the list in C# and fill it
2: Create an array in javascript
3: Use razor to iterate the list
4: Use #: to switch back to js and # to switch to C#
5: The -1 in the month to correct the month number in js.
Good luck
I did this using date time format.
C# to JS
public static class DateTimeExtension
{
public static string ToJsString(this DateTime #this)
{
return #this.ToString("ddd, dd MMM yyyy HH:mm:ss") + " GMT";
}
}
JS to C#
public DateTime ParseJSDate(this string jsDate)
{
return DateTime.ParseExact(jsDate, "ddd, dd MMM yyyy HH:mm:ss GMT", CultureInfo.InvariantCulture);
}
<input type="hidden" id="CDate" value="<%=DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")%>" />
In order to convert the date to JS date(all numbers):
var JSDate = $("#CDate").val();
JSDate = Date.parse(JSDate);