How can I convert CFAbsoluteTime to DateTime in C#? - c#

Can anyone tell me how can I convert a value which I know to be CFAbsoluteTime from MacOS into DateTime value in C#?

A CFAbsoluteTime is a double, the number of seconds since January 1st, 2001, 12am. Thus:
public static DateTime CFAbsoluteTimeToDateTime(double abs) {
long ticks = (long)(abs * 1E7); // 1 tick == 100 nsec
return new DateTime(new DateTime(2001, 1, 1).Ticks + ticks);
}

It turned out, that I can convert it using following code:
TimeSpan span = TimeSpan.FromSeconds(CFAbsoluteTimeFloatValue);
var cshartpDateTime = new DateTime(2001, 1, 1).Add(span);

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

Convert System Date and time into integer

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.

Converting TimeSpan Hours to DateTime

Commented Code As Posted by Arif Eqbal the below Converts a TimeSpan to a DateTime
A problem with 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 as specified. The minutes and seconds are preserved. ~~ Ideas on how to preserve the 2 days in the TimeSpan arguments and return them as the DateTime day?
A second problem of this conversion is that if I want to add the hours in days to the hours in the TimeSpan and return them as DateTime hours, e.g. Format = "hh:mm" or 49:30, there is no way to add the hours together in a DateTime object. Essentially I want to convert TimeSpan.TotalHours to the Hours component of the DateTime object. I understand this likely requires a string conversion, but there doesn't seem to be an elegant solution in .Net 3.5. Unfortunately I do not have the luxury of the converters from 4.0 or 4.5.
public void test()
{
// Arif Eqbal
//DateTime dt = new DateTime(2012, 01, 01);
//TimeSpan ts = new TimeSpan(1, 0, 0, 0, 0);
//dt = dt + ts;
_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
}
Thanks - Glenn
It returns "02" when I try it.
The "dd" format makes it put leading zeroes if necessary, but you have failed to account for this in your Is.EqualTo("2")
Therefore your assertion fails (but you mistakenly thought that it was returning 3).
I tested this by copy/pasting your code into a Console app:
var _ts = new TimeSpan(2, 1, 30, 10);
var format = "dd";
var returnedVal = _ts.ToString(format);
Console.WriteLine(returnedVal); // Prints "02"
[EDIT] Aha! Now I know what you've done. Your code is actually like this:
var _ts = new TimeSpan(2, 1, 30, 10);
var format = "dd";
DateTime formatDateTime = new DateTime(2012, 01, 01);
var conversionResult = formatDateTime + _ts;
string result = conversionResult.ToString(format);
But note what the type of conversionResult is DateTime, not TimeSpan.
So you're doing here is using the format "dd" with a DateTime object, and "dd" for a DateTime means "The day of the month".
So you took the date 2012-01-01 and added 2 days (and a bit) to it to make it 2012-01-03, and then you made a string out of the day of the month part, which of course is 3.
Problem explained!

What is the easiest way to subtract time in C#?

I'm trying to put together a tool that will help me make work schedules. What is the easiest way to solve the following?
8:00am + 5 hours = 1:00pm
5:00pm - 2 hours = 3:00pm
5:30pm - :45 = 4:45
and so on.
These can all be done with DateTime.Add(TimeSpan) since it supports positive and negative timespans.
DateTime original = new DateTime(year, month, day, 8, 0, 0);
DateTime updated = original.Add(new TimeSpan(5,0,0));
DateTime original = new DateTime(year, month, day, 17, 0, 0);
DateTime updated = original.Add(new TimeSpan(-2,0,0));
DateTime original = new DateTime(year, month, day, 17, 30, 0);
DateTime updated = original.Add(new TimeSpan(0,-45,0));
Or you can also use the DateTime.Subtract(TimeSpan) method analogously.
Check out all the DateTime methods here: http://msdn.microsoft.com/en-us/library/system.datetime.aspx
Add Returns a new DateTime that adds the value of the specified TimeSpan to the value of this instance.
AddDays Returns a new DateTime that adds the specified number of days to the value of this instance.
AddHours Returns a new DateTime that adds the specified number of hours to the value of this instance.
AddMilliseconds Returns a new DateTime that adds the specified number of milliseconds to the value of this instance.
AddMinutes Returns a new DateTime that adds the specified number of minutes to the value of this instance.
AddMonths Returns a new DateTime that adds the specified number of months to the value of this instance.
AddSeconds Returns a new DateTime that adds the specified number of seconds to the value of this instance.
AddTicks Returns a new DateTime that adds the specified number of ticks to the value of this instance.
AddYears Returns a new DateTime that adds the specified number of years to the value of this instance.
This works too:
System.DateTime dTime = DateTime.Now();
// tSpan is 0 days, 1 hours, 30 minutes and 0 second.
System.TimeSpan tSpan = new System.TimeSpan(0, 1, 3, 0);
System.DateTime result = dTime + tSpan;
To subtract a year:
DateTime DateEnd = DateTime.Now;
DateTime DateStart = DateEnd - new TimeSpan(365, 0, 0, 0);
Hi if you are going to subtract only Integer value from DateTime then you have to write code like this
DateTime.Now.AddHours(-2)
Here I am subtracting 2 hours from the current date and time
Use the TimeSpan object to capture your initial time element and use the methods such as AddHours or AddMinutes. To substract 3 hours, you will do AddHours(-3). To substract 45 mins, you will do AddMinutes(-45)
try this
namespace dateandtime
{
class DatesTime
{
public static DateTime Substract(DateTime now, int hours,int minutes,int seconds)
{
TimeSpan T1 = new TimeSpan(hours, minutes, seconds);
return now.Subtract(T1);
}
static void Main(string[] args)
{
Console.WriteLine(Substract(DateTime.Now, 36, 0, 0).ToString());
}
}
}
TimeLeftToOpen= new TimeSpan(TimeLeftToOpen.Hours, TimeLeftToOpen.Minutes, TimeLeftToOpen.Seconds - 1);

Categories