Date Time format issue in crunchbase API using C# - c#

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.

Related

I have the number of days (stored in SQL db as 37867) since 1900 and want to convert it to a date like "Sep-5-2003

I have a number retrieved from SQL = 37867 and need to convert it to the date it represents which is 2003-09-05.
The number 37867 represents the number of days since 1900 and the answer should be 2003-09-05 but how to calculate this in C#?
This is the SQL function that does it: "SELECT CONVERT(datetime,37867)" but how can I do it in C# so I can update that int and make it a string literal and replace that int with that string?
I am guessing that this is how the struct for Windows stores the DateTime stamp.
If I spend enough time I am pretty sure I can figure it out, but it will take more time than I really want to spend and if someone else already has...why re-invent the wheel?
This community generally prefers that you make an attempt, if we see what you were attempting to do it's generally easier to help then writing something from scratch.
Having said that:
// Create new DateTime, January 1st 1900
var dt = new DateTime(1900, 1, 1);
// Add 37867 days to that DateTime
dt = dt.AddDays(37867);
// Call ToString()
var s = dt.ToString();

Converting to epoch time-stamp adding hours offset

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;

Noda Time (C#) Magic to parse JSON (supposed ISO 8601) Date. e.g. 1396949418557

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.

C# - Formatting current time

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.

How can I compare a UTC date created in Javascript to a UTC date in C#?

I'm trying to create a UTC date in JavaScript on one server, and pass it via URL querystring to another server, where C# can take that querystring, recognize it as a date and compare it to a new C# UTC date - and it's proving trickier that I though (unless I'm just having one of those days). I don't see any other questions on stackoverflow asking this (in the 'similar titles' or 'similar questions' lists that show while typing a question).
To create the data in JavaScript I'm using the following, based on this w3schools article:
var currentDate = new Date();
var day = currentDate.getUTCDate();
var month = currentDate.getUTCMonth();
var year = currentDate.getUTCFullYear();
var hours = currentDate.getUTCHours();
var minutes = currentDate.getUTCMinutes();
var seconds = currentDate.getUTCSeconds();
var milliseconds = currentDate.getUTCMilliseconds();
var expiry = Date.UTC(month,day,year,hours,minutes,seconds,milliseconds);
the results looks like this 1311871476074
So, in C# how do I take this value from the querystring and
convert it into a proper date, and
compare it to a C# based UTC DateTime variable?
Any tips, corrections in my logic/code or links to articles would be greatly appreciated.
Kevin
UPDATE
Both the answers below helped me resolve my issue: Luke helped with the C# side of things, and Ray helped with the JavaScript - unfortunately I can't mark them both as answers, but I wish I could!
The JavaScript UTC method returns the number of milliseconds since 00:00:00 UTC on 1 January 1970. To convert those milliseconds back to a DateTime in C# you just need to add them onto that original "epoch":
string rawMilliseconds = Request.QueryString["expiry"];
if (string.IsNullOrWhiteSpace(rawMilliseconds))
throw new InvalidOperationException("Expiry is null or empty!");
long milliseconds;
if (!long.TryParse(rawMilliseconds, out milliseconds))
throw new InvalidOperationException("Unable to parse expiry!");
DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
DateTime expiry = epoch.AddMilliseconds(milliseconds);
A datetime object represents an instant in time and is usually represented internally as the number of milliseconds since the epoch. In JavaScript to get this value for the current time it is easier to use
new Date().getTime()
Now you just have a number (or a string containing a number) which you can pass to your C# application and construct a DateTime object from.
For that I can refer you to C# convert UTC int to DateTime object (Jon Skeet has an answer for it.) :)

Categories

Resources