I have date time in a string as "20160127003500".
What I need to do is convert this to Unix time-stamp adding hours to it.
I want to add hours offset as "1" or "2" or "24".
Can anyone please guide me in right direction.
Regards
First, parse the entire string (including the offset you mentioned in the question comments) to a DateTimeOffset:
using System.Globalization;
string s = "20160129205500 +0100";
string format = "yyyyMMddHHmmss zzz";
DateTimeOffset dto = DateTimeOffset.ParseExact(s, format, CultureInfo.InvariantCulture);
Then, there are a few different ways to get a Unix timestamp. Note that by the pure definition of a "Unix timestamp", the result would be in terms of seconds, though many languages these days use a higher precision (such as milliseconds used in JavaScript).
If you are targeting .NET 4.6 or higher, simply use the built-in methods:
// pick one for the desired precision:
long timestamp = dto.ToUnixTimeMilliseconds();
long timestamp = dto.ToUnixTimeSeconds();
If you are targeting an earlier version of .NET, then compute it yourself:
DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
// pick one for the desired precision:
long timestamp = (long) dto.UtcDateTime.Subtract(epoch).TotalMilliseconds;
long timestamp = (long) dto.UtcDateTime.Subtract(epoch).TotalSeconds;
Related
Does anyone know how to calculate the number of .net time ticks from outside of the .net framework? my situation involves a python script on Linux (my side) needing to send a timestamp as the number of ticks in a message destined for a C# process (the other side, who can't change its code). I can't find any libraries that do this... Any thoughts? Thanks!
You can easily determine what the Unix/Linux epoch (1970-01-01 00:00:00) is in DateTime ticks:
DateTime netTime = new DateTime(1970, 1, 1, 0, 0, 0);
Console.WriteLine(netTime.Ticks);
// Prints 621355968000000000
Since the Unix/Linux timestamp is the number of seconds since 1970-01-01 00:00:00, you can convert that to 100ns ticks by multiplying it by 10000000, and then convert it to DateTime ticks by adding 621355968000000000:
long netTicks = 621355968000000000L + 10000000L * linuxTimestamp;
I am working in crunchbase api. I have got result form Crunchbase api https://developer.crunchbase.com/docs. I did not able to parse given value of Created date and update date to Datetime format using C#
anybody help me to fix this issue ??
Those numbers are unix timestamps.
Lucky for you, conversion is pretty straightforward since they just represent the time passed in seconds since 01.01.1970
// create a new DateTime for the time timestamps start counting from
var dt = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
var dtDateTime = dt.AddSeconds(myJson.created_at).ToLocalTime();
Where myJson.created_at is your extracted date time.
Now that you realize what these attributes are, consider this question and answers that explain how to convert a unix timestamp to a C# datetime automatically as part of JSON conversion. Note that question is kind of different, you want seconds and not milliseconds like in that answer.
I cannot for the life of me deserialize a date string which I am told is ISO 8601 (e.g. '1396949418557') to a C# DateTime object.
I really like what I've read about Noda Time, and I am using JSON.NET. Has anyone come across this?
Using Noda Time:
Instant instant = Instant.FromMillisecondsSinceUnixEpoch(1396949418557);
It looks like a unix timestamp. Try this:
var unixEraStart = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var dateTime = unixEraStart.AddMilliseconds(1396949418557);
Your string looks like a Javascript timestamp (milliseconds since 1970/01/01, effectively 1000 * unix time).
I've never used nodatime, but it looks like that library defines time in terms of ticks since the unix epoch, with 10,000 ticks = 1 millisecond. So if you do an Int64.Parse of your string, then multiply it by 10,000, you should be able to construct a nodatime date object with that value.
In C#, how can I get the current DateTime in the following format? 2011-08-10T21:36:01.6327538Z
DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ")
Note that if you're not using DateTime.UtcNow and are instead using an existing DateTime instance, you may need to convert it to universal time before using the given format string (e.g. DateTime.ToUniversalTime())
Keep in mind that DateTime.Now is sometimes only precise to a thousandth of a second, depending on the system clock. This page shows the following:
It is possible to display very small fractional units of a second, such as ten thousandths of a second or hundred-thousandths of a second. However, these values may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On Windows NT 3.5 and later, and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds.
However, if you populate the DateTime yourself, you can make it more precise. I am not aware of any other built-in libraries that are more precise than DateTime.UtcNow.
Also, DateTime.UtcNow.ToString("o") will give you an ordinal datetime string. This doesn't always specify the timezone at the end, so you'd still need to add Z to the end if you knew were dealing with Utc and the DateTime format was Unspecified
If you want your times in UTC (which is what the Z implies) then you need to ensure that they are UTC times...
i.e.
DateTime.UtcNow.ToString("O");
or assuming that you know that your datetime is local...
DateTime foo = MethodThatReturnsALocalTime();
foo.ToUniversalTime().ToString("O");
FWIW: DateTime.UtcNow is faster than DateTime.Now because it doesn't need to do a timezone lookup, on Compact Framework that difference can be very noticeable for some reason.
You can try either:
DateTime.Now.ToString("o");
which also includes the timezone component. - OR -
DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss.fffffff")
Try this:
var xs = DateIime.Now;
var frmtdDatetime = xs.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffff");
and check out this msdn link
You want a date in ISO 8601 format.
Use the "O" round-trip format with a date in UTC:
// 2022-12-22T10:20:30.4567890Z
string formatted = DateTime.UtcNow.ToString("O");
If your DateTime is not marked as UTC, the round-trip format is still round-trip but the date won't have the Z at the end:
// 2022-12-22T10:20:30.4567890Z+09:00
string local = DateTime.Now.ToString("O");
// 2022-12-22T10:20:30.4567890Z
string unspecified = new DateTime(2022, 12, 24, 0, 0, 0, DateTimeKind.Unspecified).ToString("O");
We see that local times add a time offset instead of a Z, and Unspecified times cannot add any information on time offset.
This is where problems start. Don't just add a Z at the end!
Pitfall
But why can't we just add a Z at the end?
Because 10h:20m:30s local is not the same as 10h:20m:30s UTC.
Let's assume we are in Japan.
If a date is local, 11:00:00AM is actually 02:00:00Z and not 11:00:00Z.
Let's see how bad data can interfere:
long ticks = 638074368000000000L;
var utc = new DateTime(ticks, DateTimeKind.Utc);
var local = new DateTime(ticks, DateTimeKind.Local);
var unspecified = new DateTime(ticks, DateTimeKind.Unspecified);
var utcAsLocal = utc.ToLocalTime();
var localAsUtc = new DateTime(ticks, DateTimeKind.Local);
var localFromLocalClock = new DateTime(2022, 12, 24, 9, 0, 0, DateTimeKind.Local);
var utcFromLocalClock = localFromLocalClock.ToUniversalTime();
Console.WriteLine($"UTC: {utc:O}"); // 1 OK: 2022-12-24T00:00:00.0000000Z
Console.WriteLine($"Local: {local:O}"); // 2 ??: 2022-12-24T00:00:00.0000000+09:00
Console.WriteLine($"Unspecified: {unspecified:O}"); // 3 OK: 2022-12-24T00:00:00.0000000
Console.WriteLine($"UTC>Local: {utcAsLocal:O}"); // 4 OK: 2022-12-24T09:00:00.0000000+09:00
Console.WriteLine($"Local>Utc: {localAsUtc:O}"); // 5 ??: 2022-12-24T00:00:00.0000000+09:00
Console.WriteLine($"!Local: {localFromLocalClock:O}"); // 6 OK: 2022-12-24T09:00:00.0000000+09:00
Console.WriteLine($"!UTC: {utcFromLocalClock:O}"); // 7 OK: 2022-12-24T00:00:00.0000000Z
Notice that the local date does not represent the same universal instant as the UTC and Unspecified datetimes! Lines 2 and 5 are actually different instants.
The localFromLocalClock does.
So if we get a date that is not in UTC and just format it either without timezone or adding a Z, we're corrupting the data.
We often become vulnerable to bugs due to this. We should be careful when manipulating dates.
This is why your UTC requirement for the date is important.
Suggested reading
The Noda Time API was built (by Jon Skeet!) to deal with this.
It presents a good set of data structures that ensure that we work with dates correctly.
I'm working with pbx for voip calls. One aspect of pbx is that you can choose to receive CDR packages. Those packages have 2 timestamps : "utc" and "local", but both seem to always be the same.
Here's an example of a timestamp : "1268927156".
At first sight, there seems to be no logic in it. So I tried converting it several ways, but with no good result. That value should provide a time around 11am (+1GMT) today.
Things I tried:
Datetime dt = new Datetime(number);
Timespan ts = new Timespan(number);
DateTime utc = new DateTime(number + 504911232000000000, DateTimeKind.Utc)
and some others I can't remember right now.
Am I missing something stupid here?
Thanks in advance
This looks like Unix time.
1268927156 = Thu, 18 Mar 2010 15:45:56 GMT
And a code sample:
DateTime startDate = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
DateTime time = startDate.AddSeconds(1268927156 );
Seems to be a Unix timestamp (no. of seconds since the epoch)
DateTime translated = new DateTime(1970,1,1).AddSeconds(1268927156);
should give you the date and time you were after...
That looks like a unix timestamp, which is the no. of seconds since Jan 01,1970.
DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(1268927156);
If both the utc and local timestamps are the same, the timezone on your PBX is either set to UTC, and your timestamps really are UTC, or the timezone is set to UTC but the time is set to your local time, and you get your local time for both of the timestamps. You'll have to figure out which of those so you'll know wether to convert the timestamps from UTC or not.
I guess this is a UNIX timestamp, the logic would be the following:
The UNIX timestamp represents the time measured in number of seconds since the Unix Epoch (1st of January 1970 00:00:00 GMT)
There is a codeproject article explaining the conversion. Basically what you need to do would be the following:
// First make a System.DateTime equivalent to the UNIX Epoch.
System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
// Add the number of seconds in UNIX timestamp to be converted.
dateTime = dateTime.AddSeconds(timestamp);