I'm trying to convert this unix timestamp
1415115303410
in DateTime, in this way:
private static DateTime UnixTimeStampToDateTime(long unixTimeStamp)
{
System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
dtDateTime = dtDateTime.AddMilliseconds(unixTimeStamp);
return dtDateTime;
}
But I get a wrong date:
Date: {04/11/0045 00:00:00}
NOTE: dtDateTime.AddSeconds(unixTimeStamp) throws an exception.. my number is in Milliseconds.
with this online conversion tool http://www.epochconverter.com/ I get the right conversion:
04/11/2014 15:35:03 GMT+0:00
How I can convert this one?
Your code is working just fine, as is. Here is a fiddle.
Everyone that is telling you to use AddSeconds is wrong. The number you are giving us is clearly in milliseconds. There are 31,536,000 seconds in a year. 1415115303410 divided by 31536000 is 4487. There hasn't been 4,487 years passed since 1/1/1970.
use AddSeconds instead of AddMilliseconds
private static DateTime UnixTimeStampToDateTime(long unixTimeStamp)
{
System.DateTime dtDateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
dtDateTime = dtDateTime.AddSeconds(unixTimeStamp);
return dtDateTime;
}
Just use DateTimeOffset
DateTimeOffset date = DateTimeOffset.FromUnixTimeSeconds(1415115303410)
public DateTime FromUnixTime(long unixTime)
{
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return epoch.AddMilliseconds(unixTime);
}
var date = FromUnixTime(1415115303410); // 11/4/2014 3:35:03 PM
Since your number is in milliseconds, Unix time, use AddMilliseconds.
Try This
DateTime date = new DateTime(Convert.ToInt64("1415115303410"));
Microsoft continue thinking about us! All solutions to add seconds/milliseconds is not working with Visual Studio 2017 (.Net 4.6.1). But there is a new solution:
public static DateTime numStrToDate(String val)
{
DateTime dRet = new DateTime(1970, 1, 1, 0, 0, 0, 0);
long dSec;
if (long.TryParse(val, out dSec))
{
TimeSpan ts = new TimeSpan(dSec*10l);
dRet = dRet.Add(ts);
}
return dRet;
}
If you need a UTC time - just add 'System.DateTimeKind.Utc' to the DateTime constructor call.
Date to Timestamp
DateTime date = DateTime.ParseExact(date_string, "dd/MM/yyyy H:mm:ss", null);
Double timestamp = Math.Truncate((date.ToUniversalTime().Subtract(new DateTime(1970, 1, 1))).TotalSeconds);
Timestamp to Date
DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Unspecified);
dtDateTime = dtDateTime.AddSeconds(Double.Parse(arrayFinalResponse[i, 5])).ToLocalTime();
String date = dtDateTime.ToString("dd/MM/yyyy H:mm:ss", CultureInfo.GetCultureInfo("en-US"));
You can do the conversion by using a little trick with date command.
It does depend on your timezone. I live in UTC + 1 so for me it is like this:
h1x1binax:~ # date -d "Thu Jan 1 01:00:00 CET 1970 + 1415115303410 second"
Thu Mar 21 09:16:50 CET 46813
h1x1binax:~ #
So that's not a unixtime timestamp ... it is probably in milliseconds so need to divide by 1000
h1x1binax:~ # date -d "Thu Jan 1 01:00:00 CET 1970 + 1415115303 second"
Tue Nov 4 16:35:03 CET 2014
h1x1binax:~ #
Related
i am trying to convert current year + 1 midnight date time to unix timestamp.
for that i have tried
DateTime currentTime = DateTime.Today;
DateTime yearEnd = new DateTime( currentTime.Year, 1,1,currentTime.Minute,currentTime.Hour,currentTime.Second,DateTimeKind.Local);
yearEnd = yearEnd.AddYears(1);
double t = (yearEnd.ToUniversalTime() - new DateTime(1970, 1, 1,0,0,0)).TotalMilliseconds;
and above code is returning 1514782800000 i.e. Mon Jan 01 2018 05:00:00 UTC in and Mon Jan 01 2018 10:30:00 Local (india)
what i am expecting is it converts time to Mon Jan 01 2018 00:00:00 local time
By default DateTime creates Unspecified DateTimeKind, so using UTC explicitly helps to avoid confusion. I've tried to rewrite in this way
DateTime currentTime = DateTime.UtcNow;
DateTime yearEnd = new DateTime( currentTime.Year, 1,1,0,0,0, DateTimeKind.Utc);
yearEnd = yearEnd.AddYears(1); // output DateTime has Utc Kind
var unixTimestamp = (yearEnd.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc))).TotalMilliseconds;
Console.WriteLine(unixTimestamp);
The output is 1514764800000 which converts to GMT: Monday, 1 January 2018 00:00:00
Update:
In case you need to convert timestamp back to DateTime you may use the following:
public static DateTime UnixTimeStampToDateTime(double unixTimeStamp)
{
System.DateTime dtDateTime = new DateTime(1970,1,1,0,0,0,0,System.DateTimeKind.Utc);
dtDateTime = dtDateTime.AddMilliseconds(unixTimeStamp);
return dtDateTime; // still Utc Kind
}
Usage example if you need to convert to other timezone:
TimeZoneInfo infotime = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time (Mexico)"); // specify your desired timezone here
Console.WriteLine(TimeZoneInfo.ConvertTimeFromUtc(UnixTimeStampToDateTime(unixTimestamp), infotime));
if i understand you right you want the following:
double result = new DateTime(currentTime.Year + 1, 1, 1, 0, 0, 0, DateTimeKind.Local).Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;
Or improved for readablity
DateTime newYear = new DateTime(currentTime.Year + 1, 1, 1, 0, 0, 0, DateTimeKind.Utc);
DateTime uTSBegin = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
double result2 = newYear.Subtract(uTSBegin).TotalSeconds;
I need to convert Cocoa NSDate to C# DateTime and vice versa.
I am using the following method to achieve this:
public static DateTime NSDateToDateTime (Foundation.NSDate date)
{
DateTime reference = TimeZone.CurrentTimeZone.ToLocalTime (
new DateTime (2001, 1, 1, 0, 0, 0));
return reference.AddSeconds (date.SecondsSinceReferenceDate);
}
public static Foundation.NSDate DateTimeToNSDate (DateTime date)
{
DateTime reference = TimeZone.CurrentTimeZone.ToLocalTime (
new DateTime (2001, 1, 1, 0, 0, 0));
return Foundation.NSDate.FromTimeIntervalSinceReferenceDate (
(date - reference).TotalSeconds);
}
But it turns out, this way it is not accounting for Daylight Saving.
Eg. DateTime object in which the time was 5AM in DST returns NSDate with time 6AM.
I'm pretty sure this is an outdated approach. You can cast a NSDate directly to a DateTime now.
Foundation.NSDate nsDate = // someValue
DateTime dateTime = (DateTime)nsDate;
Based on inputs from:
https://forums.xamarin.com/discussion/27184/convert-nsdate-to-datetime
Local Time changes during Daylight Saving.
Hence, always convert to UTC to do the calculations, then convert to Local time if needed.
public static DateTime NSDateToDateTime (Foundation.NSDate date)
{
DateTime reference = new DateTime(2001, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
var utcDateTime = reference.AddSeconds(date.SecondsSinceReferenceDate);
return utcDateTime.ToLocalTime();
}
public static Foundation.NSDate DateTimeToNSDate (DateTime date)
{
DateTime reference = new DateTime(2001, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
var utcDateTime = date.ToUniversalTime();
return Foundation.NSDate.FromTimeIntervalSinceReferenceDate((utcDateTime - reference).TotalSeconds);
}
There is a creepy bug on direct casting to NSDate
My solution was:
public static NSDate DateTimeToNSDate(this DateTime date)
{
var calendar = new NSCalendar(NSCalendarType.Gregorian);
calendar.TimeZone = NSTimeZone.FromName("UTC");
var components = new NSDateComponents { Day = date.Day, Month = date.Month, Year = date.Year, Hour = date.Hour,
Minute = date.Minute, Second = date.Second, Nanosecond = date.Millisecond * 1000000 };
var result = calendar.DateFromComponents(components);
return result;
}
I hope this helps
Given this datetime of January 1 2015 at 23:00 hours:
var someDate = new DateTime(2015, 1, 1, 23, 0, 0);
And given the int 6, which is the desired hour, how do I return the first following datetime where the hour is 6? In this case, someDate and 6 would return a new DateTime of January 2 2015 at 06:00 hours.
I would simply add the hours to the original date and add another day if the result is before the original time:
var someDate = new DateTime(2015, 1, 1, 23, 0, 0);
var result = someDate.Date.AddHours(6); // note the "Date" part
if (result < someDate) result = result.AddDays(1);
You just have to add one day to the date and six hours to the result:
var someDate = new DateTime(2015, 1, 1, 23, 0, 0);
var result = someDate.Date.AddDays(1).AddHours(6);
Note the use of Date property - it will give you the start od the day and from there it's easy to navigate forward.
Try this:
while(someDate.Hour != 6){
someDate = someDate.AddHours(1);
}
Assuming you meant 24h clock, you can try this:
public DateTime GetDate(DateTime someDate,int hour)
{
return someDate.Hour>=hour? someDate.Date.AddDays(1).AddHours(6):someDate.Date.AddHours(6);
}
Something like this should do it:
public DateTime FollowingHour(DateTime start, int hour)
{
DateTime atHour = start.Date.AddHours(6);
if(atHour < start)
{
atHour += TimeSpan.FromDays(1);
}
return atHour;
}
For example 1297380023295 should be 2010/2/11 9 AM
I use this code right now
long dateNumber = num;
long beginTicks = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;
DateTime dateValue = new DateTime(beginTicks + dateNumber * 10000);
return dateValue;
The result of this function is 1 AM,It is GMT.
What can I do with it?
You're looking for the ToLocalTime() method:
long unixDate = 1297380023295;
DateTime start = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
DateTime date= start.AddMilliseconds(unixDate).ToLocalTime();
long a= 634792557112051692;
//a= ticks time
DateTime dt = new DateTime(a);
Response.Write(dt.Hour.ToString());
//dt.hour convert time ticks to time hour
You can specify the DateTimeKind when you create a new DateTime object, so you could specify that as UTC and then use .ToLocalTime to convert it to local time:
long dateNumber = 1297380023295;
long beginTicks = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;
DateTime dt = new DateTime(beginTicks + dateNumber * 10000, DateTimeKind.Utc);
MessageBox.Show(dt.ToLocalTime().ToString());
U can use static methods from DateTimeOffset.
DateTimeOffset.FromUnixTimeSeconds()
DateTimeOffset.FromUnixTimeMilliseconds()
Depends in wich format you have your ticks.
and if u want DateTime you can use for example
var ticks = 1635091250;
var dateTime = DateTimeOffset.FromUnixTimeSeconds(ticks).DateTime;
Powershell script piece, just FYI
$minDate = New-Object "System.DateTime"
$minDate = $minDate.AddYears(1969)
$minDate.AddMilliseconds(1446616420947)
In C# 3.0, how do I get the seconds since 1/1/2010?
Goes like this:
TimeSpan test = DateTime.Now - new DateTime(2010, 01, 01);
MessageBox.Show(test.TotalSeconds.ToString());
For one liner fun:
MessageBox.Show((DateTime.Now - new DateTime(2010, 01, 01))
.TotalSeconds.ToString());
You can substract 2 DateTime instances and get a TimeSpan:
DateTime date = new DateTime(2010,1,1);
TimeSpan diff = DateTime.Now - date;
double seconds = diff.TotalSeconds;
Just to avoid timezone issues
TimeSpan t = (DateTime.UtcNow - new DateTime(2010, 1, 1));
int timestamp = (int) t.TotalSeconds;
Console.WriteLine (timestamp);
It's really a matter of whose 2010-Jan-01 you're using and whether or not you wish to account for daylight savings.
//I'm currently in Central Daylight Time (Houston, Texas)
DateTime jan1 = new DateTime(2010, 1, 1);
//days since Jan1 + time since midnight
TimeSpan differenceWithDaylightSavings = DateTime.Now - jan1;
//one hour less than above (we "skipped" those 60 minutes about a month ago)
TimeSpan differenceWithoutDaylightSavings = (DateTime.UtcNow - jan1.ToUniversalTime());
//difference for those using UTC and 2010-Jan-01 12:00:00 AM UTC as their starting point
// (today it's 5 hours longer than differenceWithDaylightSavings)
TimeSpan utcDifference = (DateTime.UtcNow - new DateTime(2010, 1, 1));
Difference with Daylight Savings: 105.15:44:09.7003571
Difference without Daylight Savings: 105.14:44:09.7003571
UTC Difference: 105.20:44:09.7003571
To get the seconds, use the TotalSeconds property off the TimeSpan object.
protected void Page_Load(object sender, EventArgs e)
{
SecondsSinceNow(new DateTime(2010, 1, 1, 0, 0, 0));
}
private double SecondsSinceNow(DateTime compareDate)
{
System.TimeSpan timeDifference = DateTime.Now.Subtract(compareDate);
return timeDifference.TotalSeconds;
}
DateTime t1 = DateTime.Now;
DateTime p = new DateTime(2010, 1, 1);
TimeSpan d = t1 - p;
long s = (long)d.TotalSeconds;
MessageBox.Show(s.ToString());