Get shortTimeDate from Unix format (C#) - 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

Related

How to parse datetime without date in C#?

If I have a string like 15:00 and I parse this to DateTime ot DateTimeOffset, the date is set to today.
I want somehow to distinguish, if the date part is given or not. It would help, if the date part is not given, the date is 1.1.1970.
Is there a better possibility instead of using regex and parse this by my own?
Try to parse the value as TimeSpan and then try to parse it as DateTime.
var data = "15:00";
if (TimeSpan.TryParse(data, out var time))
{
Console.WriteLine("Time: {0}", time);
}
else if (DateTime.TryParse(data, out var datetime))
{
Console.WriteLine("DateTime: {0}", datetime);
}
else
{
Console.WriteLine("I don't know how to parse {0}", data);
}
If I have a string like "15:00" and I parse this to DateTime ot
DateTimeOffset, the date is set to today.
This is by design.
From DateTime.Parse doc:
A string with a time but no date component. The method assumes the
current date unless you call the Parse(String, IFormatProvider,
DateTimeStyles) overload and include
DateTimeStyles.NoCurrentDateDefault in the styles argument, in which
case the method assumes a date of January 1, 0001.
From DateTimeOffset.Parse doc:
If is missing, its default value is the current day.
So, for DateTime, if you don't use any DateTimeStyles, you get the current date
var hours = "15:00";
var date = DateTime.Parse(hours, CultureInfo.InvariantCulture); // 12/9/2018 3:00:00 PM
but if you use DateTimeStyles.NoCurrentDateDefault as a third parameter;
var hours = "15:00";
var date = DateTime.Parse(hours, CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault);
// 1/1/0001 3:00:00 PM
But I think your problem keeps on that sentence; "if the date part is given or not.." How did you decide your string has date part or not? Is it always have 5 characters as Steve commented? It can be in a format like 4:00? What about 4:1? If it can be like 4:1, it should be parsed as 4:10 or 4:01?
So, you need to decide first what is the meaning of "if the date part is given or not.." for your case. Then you can easily parse your string to TimeSpan, not DateTime in my opinion, so, you can add it created manually "1.1.1970" with DateTime(int, int, int) constructor.
if(YourConditionForYourStringNotIncludingDatePart)
{
var time = TimeSpan.Parse("15:00");
var date = new DateTime(1970, 1, 1);
var result = date.Add(time);
}
Using regular expressins for DateTime parsing is usually a bad idea. I wouldn't suggest to use it unless you have no other way to do it for DateTime.
I think for that case you could things keep simple. This could be a solution that not depends on the lenght when there is only a timepart:
void Main()
{
Console.WriteLine(ParseWithDummyIfDateAbsent("15:00", new DateTime(1970, 1, 1)));
Console.WriteLine(ParseWithDummyIfDateAbsent("15:00:22", new DateTime(1970, 1, 1)));
Console.WriteLine(ParseWithDummyIfDateAbsent("09.12.2018 15:00", new DateTime(1970, 1, 1)));
}
DateTime ParseWithDummyIfDateAbsent(string input, DateTime dummyDate)
{
if(TimeSpan.TryParse(input, out var timeSpan))
input = $"{dummyDate.Date.ToShortDateString()} {input}";
return DateTime.Parse(input);
}
Output:
01.01.1970 15:00:00
01.01.1970 15:00:22
09.12.2018 15:00:00
Depends on your localization:-)

JavaScriptSerializer :After serialization Date becomes less by one day [duplicate]

I am using JavaScriptSerializer for serializing DateTime, but when I deserialize it show one day less from the date it get serialize:
Here is test:
DateTime startDate=new DateTime(2012,1,20);//set the 20th of January
JavaScriptSerializer serializer=new JavaScriptSerializer();
string serializeDate= serializer.Serialize(startDate);
DateTime afterDeserialize= serializer.Deserialize<DateTime>(serializeDate);//I get 19th of Jan
Assert.Equals(startDate, afterDeserialize);
firstly I thougt it because of javascript datetime format but as I know for javascript Month is zero index 0=January, but I am getting one day less than the original date.
It's not losing a day arbitrarily, it's converting to a UTC date (or I should say using the date in a UTC date format) so when it's unserialized it you're no longer within your personal time zone. It's basically performing:
DateTime whateverDate = /* incoming date */;
long ticks = whateverDate.ToUniversalTime() // make UTC
.Subtract(new DateTime(1970, 1, 1)) // subtract UNIX Epoch
.TotalMilliseconds(); // get milliseconds since then
// push in to the "\/Date(ticks)\/" format
String value = String.Format(#"\/Date({0})\/", ticks);
However, try the following:
// or you rely on it serializing, then bring it back to your own local time
// (apply the time zone).
afterDeserialize = afterDeserialize.ToLocalTime();
You'll now have the UTC time back to your local time (with time zone applied).
To Pass your test:
DateTime startDate = new DateTime(2012,1,20);
JavaScriptSerializer serializer = new JavaScriptSerializer();
String serializeDate = serializer.Serialize(startDate);
DateTime afterDeserialize = serializer.Deserialize<DateTime>(serializeDate)
.ToLocalTime(); // Note: this is added
Assert.Equals(startDate, afterDeserialize); // pass!
I had the same problem and solved it by using
Newtonsoft.Json.JsonConvert.SerializeObject()
instead of
new System.Web.Script.Serialization.JavaScriptSerializer().Serialize().
The latter call stores your DateTime converted to some random timezone (GMT+0 seems to be hardcoded).
On deserializing JavaScriptSerializer giving me output in UTC (Universal Time) which due to change in hours change the date. As Brad Christie suggested to change DateTime to UTC it can solve the problems.
But actually there is no need to change the:
DateTime startDate = new DateTime(2012, 1, 20).ToUniversalTime();
as it is already taking it as Universal Time. So I just convert the output of deserialize to LocalTime:
DateTime afterDeserialize= serializer.Deserialize<DateTime>(serializeDate);
afterDeserialize.ToLocalTime();
it solved the issue.

Computing milliseconds since 1970 in C# yields different date than JavaScript

I need to compute the JavaScript getTime method in C#.
For simplicity, I chose a fixed date in UTC and compared the C#:
C#
DateTime e = new DateTime(2011, 12, 31, 0, 0, 0, DateTimeKind.Utc);
DateTime s = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
TimeSpan t = (e - s);
var x = t.TotalMilliseconds.ToString();
=> 1325289600000
and the JavaScript results:
JavaScript
var d = new Date(2011, 12, 31, 0, 0, 0)
var utcDate = new Date(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds());
utcDate.getTime()
=> 1327960800000
Any hints on what I'm doing wrong?
Thanks!
Javascript months are zero-based.
12 means January of next year.
You want 11.
If you meant for the input to be at UTC, you should be doing this instead:
var ts = Date.UTC(2011,11,31,0,0,0);
As SLaks pointed out, months run 0-11, but even then - you must initialize the date as UTC if you want the response in UTC. In your code, you were initializing a local date, and then converting it to UTC. The result would be different depending on the time zone of the computer where the code is running. With Date.UTC, you get back a timestamp - not a Date object, and it will be the same result regardless of where it runs.
From Chrome's debugging console:
This is the same value returned from your .NET code, which looks just fine, except I would return a long, not a string.
The date JS is wrong I believe. Omit the var utcDate line and output just d.getTime()
The time between two dates is the same, regardless of timezone and offset. Timezones are relative to an ACTUAL point in time, so whether you call .getTime() on the UTC or EST or PST date, it will be the same relative to 1970-1-1 of the same timezone.
2011-12-31 EST - 1970-1-1 EST
== 2011-12-31 PST - 1970-1-1 PST
== 2011-12-31 UTC - 1970-1-1 UTC
EDIT: Per #Slaks above, you also are not using the 0-based month (which I also had no idea about).

Convert datetime from xml datetime to epoch format

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.)

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.

Categories

Resources