Convert datetime from xml datetime to epoch format - c#

I'm feeding an android application with a xml having a datetime attribute.
Problem here is, the application is accepting datetime by 13 digit number like 1347712845061. I'm not able to find an options to do this type of conversion in c#.
Do anyone have any suggestion?

Assuming that sample value was meant to be Sat, 15 Sep 2012 12:40:45 UTC, it just means "number of milliseconds since the Unix epoch". (That's the information within a java.util.Date.) So you can write:
private static readonly DateTime UnixEpoch =
new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public static DateTime FromJavaDate(long millisSinceEpoch)
{
return UnixEpoch.AddMilliseconds(millisSinceEpoch);
}
(You could use a DateTimeOffset too, which would always have an offset of 0.)

Related

Get shortTimeDate from Unix format (C#)

I have time input data as below:
1536271200
1536184800
1536098400
1536012000
1535925600
I made quick Unix TimeConverter:
public static DateTime Converter(double ts)
{
DateTime org= new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
org = org.AddSeconds(ts);
org = org.ToLocalTime();
return org;
}
but after convert it return me date as below:
2018-09-10 00:00:00
2018-09-07 00:00:00
2018-09-06 00:00:00
2018-09-05 00:00:00
2018-09-04 00:00:00
2018-09-03 00:00:00
How to get shortDateFormat (YYYY-MM-DD)?
You can use .ToString(format) to get what ever format you want, and in this case it would be .ToString("yyyy-MM-dd"):
public static string Converter(double ts)
{
DateTime org= new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
org = org.AddSeconds(ts);
org = org.ToLocalTime();
return org.ToString("yyyy-MM-dd");
}
and of course the function's return type must be string.
You're getting confused between a DateTime object, and a "text string that looks like a date"
Your DateTime object holds the instant in time that the date is. You can make it into a text string that looks like whatever you want by using .ToString() and a format string:
https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings
https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings
Or you can use one of the provided shortcut methods for standard format strings, like .ToShortDateString()
https://learn.microsoft.com/en-us/dotnet/api/system.datetime?view=netframework-4.7.2
Ultimately, what you need to appreciate is that you're complaining "my date has a time tacked on the end" -> datetimes always have a time component. There is no date in this world, your birthday, your grad day, new year's day etc that does NOT have a time associated with it.
Everything happens at a time, on a date.
When you told your program to print those dates out to the console, it included the times (all midnight) because that's what your system does by default. If you want to print them out without the times, specify a format that doesn't include time placeholders.. It is in the process of preparing data for display, that we choose what we want to see

Inconsistent DateTime to Unix Time conversion and error on 24 hour input

Attached is a method I am currently using that takes in a list of DateTime strings, their input format (i.e. yyyy-MM-dd HH:mm:ss), and their offset in the form of hours.
As for the culture and "standard", I am using InvariantCulture and I am converting the times to UTC.
public int unixFormat3(string dateTimeInput, string inputFormat, int hours)
{
DateTime result;
CultureInfo provider = CultureInfo.InvariantCulture;
result = DateTime.ParseExact(dateTimeInput, inputFormat, provider);
int unixTime = (Int32)(result.ToUniversalTime().AddHours(hours).Subtract(new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc))).TotalSeconds;
return unixTime;
}
Two issues with said method:
I am using this website as a comparison. If my input is 2014-03-18 21:00:00, my output, according to my method, is 1395190800, which converts back to 2014-03-19 01:00:00. It has a four hour difference. The desired output is this:
If my input is 2014-03-18 24:00:00, I get this error:
The DateTime represented by the string is not supported in calendar System.Globalization.GregorianCalendar.
Noticeably, it does not allow the input of 24 in the HH part. This is a weird error as NodaTime handles it just fine... Though that's irrelevant as I am using DateTime.
Does anyone have any insight on this area?
EDIT:
Upon some experimentation, removing the .ToUniversalTime() removes my 4-hour offset.. Why is this happening?
public int unixFormat3(string dateTimeInput, string inputFormat, int hours)
{
DateTime result;
CultureInfo provider = CultureInfo.InvariantCulture;
result = DateTime.ParseExact(dateTimeInput, inputFormat, provider);
int unixTime = (Int32)(result.AddHours(hours).Subtract(new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc))).TotalSeconds;
return unixTime;
}
This document, http://www.w3.org/TR/NOTE-datetime, cited in this question How to know whether a given string is a valid UTC DateTime format? does not list 24 as a valid hour value.
This document, http://en.wikipedia.org/wiki/Iso8601, cited by an answer to the question does list 24:00 as a valid time. This one, http://en.wikipedia.org/wiki/12-hour_clock#Confusion_at_noon_and_midnight, also says 24:00 is valid.
The System.DateTime object represents hours as an integer value between 0 and 23 (see http://msdn.microsoft.com/en-us/library/vstudio/system.datetime.hour(v=vs.100).aspx). As far as I know, NodaTime doesn't use any of the .NET provided DateTime or DateTimeOffset classes and handles everything itself, which is why it's handling an hour of 24 correctly.
As for why ToUniversalTime() is adding an offset, its probably because the ParseExact is returning a date that's already been adjusted. (What is the value of result just before you call ToUniversalTime()?)
You may also want to change your call to use this overload of ParseExact instead:
result = DateTime.ParseExact(dateTimeInput, inputFormat, provider, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
This tells the parser to assume the time is in UTC if no time zone is specified in the parsed string.
As a side note, you should probably declare your Unix epoch as a readonly global variable somewhere and use TryParseExact instead of ParseExact.
public class UnixTime
{
public static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
public int unixFormat3(string dateTimeInput, string inputFormat, int hours)
{
int unixTime = -1;
DateTime result = DateTime.MinValue;
if (DateTime.TryParseExact(dateTimeInput, inputFormat, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out result))
{
unixTime = (int)(result.AddHours(hours).Subtract(UnixTime.Epoch)).TotalSeconds;
}
return unixTime;
}
}

DateTime format with REST and json

I'm having a huge problem trying to figure out a json response from a REST endpoint I'm getting information from.
The date that is coming back looks like this 1319068800000
if I attempt to convert this value like so:
DateTime currentServerTime = DateTime.FromFileTimeUtc(1319068800000);
I get this output: 1/2/1601 12:38:26 PM ...obviously wrong :(
The REST endpoint I'm using has a cool HTML display of the json response, and their format of the same value looks like this: 2011/10/20 00:00:00 UTC
Can someone please shed some light on this for me? I'm trying to update the date through this REST API and when I send a date using this code
DateTime.Now.ToFileTimeUtc().ToString();
I get this result 129691518811163201, and when I send this to the API it bombs out saying I have an valid date. Thanks!
Both #Bill and #Christofer are right. You still need to convert the Unix time to a DateTime, though. Here's a small function that does this: Convert a Unix timestamp to a .NET DateTime
Code quoted from the site (by Simone Chiaretta):
static DateTime ConvertFromUnixTimestamp(double timestamp)
{
DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
return origin.AddSeconds(timestamp);
}
static double ConvertToUnixTimestamp(DateTime date)
{
DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
TimeSpan diff = date - origin;
return Math.Floor(diff.TotalSeconds);
}
It looks like the number of milliseconds since Jan 1, 1970 12:00 am GMT. This is the internal timestamp format that is typically used in Java.
user=> (java.util.Date. 1319068800000)
Date Wed Oct 19 20:00:00 EDT 2011
You can divide the returned number with 1000 before converting it to a DateTime. It seems to be returned as milliseconds since Unix epoch.

C# query datetime off sqlite database fails

I am reading a sqlite file in which datetime column data are saved as integer values (INTEGER NO NULL)
DateTime dt=reader.GetDateTime(nColDateTime);
But it emits an error saying that the return value is not in correct format.
I try out all other available methods in Datetime class and find only
DateTime dt=DateTime.FromBinary(reader.GetInt64(nColDateTime));
works (as others return exceptions).
But the formatted date (as dt.ToShortDateTime()) is incorrect (ie 0042/11/20) I have no idea what this is.
I then try this
long d=DateTime.Now.Ticks-reader.GetInt64(nColDateTime);
DateTime dt=new DateTime(d);
It gives me 1970/05/18
Could you help me to get the correct datetime ?
Your dates are stored in the Unix epoch format.
You probably just want to use:
private static readonly DateTime epoch = new DateTime(1970, 1, 1);
...
var myDate = epoch + TimeSpan.FromTicks(reader.GetInt64(nColDateTime));
For example, when I look at your example above "1970/05/18", I can assume that your date is approximately 5 months, 18 days earlier than today.
Here is how I would retreieve the original value:
(DateTime.Today - new DateTime(1970, 5, 18)).Ticks
Which returns:
13119840000000000
Plugging that into my formula:
new DateTime(1970, 1, 1) + TimeSpan.FromTicks(13119840000000000)
This returns:
2011/07/30

DateTime's representation in milliseconds?

I have a SQL-server timestamp that I need to convert into a representation of time in milliseconds since 1970. Can I do this with plain SQL? If not, I've extracted it into a DateTime variable in C#. Is it possible to get a millisec representation of this ?
Thanks,
Teja.
You're probably trying to convert to a UNIX-like timestamp, which are in UTC:
yourDateTime.ToUniversalTime().Subtract(
new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
).TotalMilliseconds
This also avoids summertime issues, since UTC doesn't have those.
In C#, you can write
(long)(date - new DateTime(1970, 1, 1)).TotalMilliseconds
As of .NET 4.6, you can use a DateTimeOffset object to get the unix milliseconds. It has a constructor which takes a DateTime object, so you can just pass in your object as demonstrated below.
DateTime yourDateTime;
long yourDateTimeMilliseconds = new DateTimeOffset(yourDateTime).ToUnixTimeMilliseconds();
As noted in other answers, make sure yourDateTime has the correct Kind specified, or use .ToUniversalTime() to convert it to UTC time first.
Here you can learn more about DateTimeOffset.
There are ToUnixTime() and ToUnixTimeMs() methods in DateTimeExtensions class
DateTime.UtcNow.ToUnixTimeMs()
SELECT CAST(DATEDIFF(S, '1970-01-01', SYSDATETIME()) AS BIGINT) * 1000
This does not give you full precision, but DATEDIFF(MS... causes overflow. If seconds are good enough, this should do it.
This other solution for covert datetime to unixtimestampmillis C#.
private static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public static long GetCurrentUnixTimestampMillis()
{
DateTime localDateTime, univDateTime;
localDateTime = DateTime.Now;
univDateTime = localDateTime.ToUniversalTime();
return (long)(univDateTime - UnixEpoch).TotalMilliseconds;
}
Using the answer of Andoma, this is what I'm doing
You can create a Struct or a Class like this one
struct Date
{
public static double GetTime(DateTime dateTime)
{
return dateTime.ToUniversalTime().Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
}
public static DateTime DateTimeParse(double milliseconds)
{
return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(milliseconds).ToLocalTime();
}
}
And you can use this in your code as following
DateTime dateTime = DateTime.Now;
double total = Date.GetTime(dateTime);
dateTime = Date.DateTimeParse(total);
I hope this help you

Categories

Resources