C# Converting string to DateTime without using DateTimeOffset - c#

I'm trying to bring over facebook events to my website. They will be coming from different regions. For example, an event is in Eastern Time (-4 hours difference from UTC) and my local time is Central time (-5 hours difference from UTC).
I am calling their graph API from a console app. I get the date of the events like this:
// get event items
me = fbClient.Get(url);
var startTime = me["start_time"];
var endTime = me["end_time"];
the start time shows: "2017-04-30T13:00:00-0400" object {string}
When I try to convert that string into a DateColumn type, it changes the output time to:
var dateTime = Convert.ToDateTime(startTime);
{4/30/2017 12:00:00 PM}
It shifted the hour from 13 -> 12, how do I convert the string into date using DateTime and not using DateTimeoffset?
This examples shows how to do it using DateTimeOffset, but I need mine in DateTime type?
https://stackoverflow.com/a/19403747/1019042

You can use the DateTime property of DateTimeOffset like the answer accepted in the link you've provided.
Or, if you really like to do it just with DateTime you can if you cut the timezone from the string:
var dt = DateTime.ParseExact(startTime.Substring(0,19),
"yyyy-MM-ddTHH:mm:ss",
CultureInfo.InvariantCulture);

Related

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.

Handling Time over TimeZones

I am attempting to convert this string time value 2017-01-10T13:19:00-07:00 to local time (Eastern). Now from my research 07:00 is Mountain Time which is 2 hours beind Eastern Time (my local). However, when I run this syntax to convert the returned output is 01/17/2017 10:19:00 AM which is 3 hours difference, not 2.
This is my syntax I am using, is this set-up incorrectly? What should I change in order to have the accurate local time returned from the UTC time?
static void Main(string[] args)
{
string green = "2017-01-10T13:19:00-07:00";
DateTime iKnowThisIsUtc = Convert.ToDateTime(green);
DateTime runtimeKnowsThisIsUtc = DateTime.SpecifyKind(
iKnowThisIsUtc,
DateTimeKind.Utc);
DateTime localVersion = runtimeKnowsThisIsUtc.ToLocalTime();
Console.WriteLine(localVersion);
Console.ReadKey();
}
EDIT
I have verified my computer is set to the correct time zone by using the following syntax which produces Eastern for both (which is correct)
TimeZone zone = TimeZone.CurrentTimeZone;
string standard = zone.StandardName;
string daylight = zone.DaylightName;
Console.WriteLine(standard);
Console.WriteLine(daylight);
Convert the string to a DateTime object:
var datetime = DateTime.Parse("2017-01-10T13:19:00-07:00");
Get the timezone for EST:
var easternZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
Convert to EST (note the conversion .ToUniversalTime()):
var easternTime = TimeZoneInfo.ConvertTimeFromUtc(datetime.ToUniversalTime(), easternZone);
Output of easternTime.ToString();:
10/01/2017 15:19:00
(I'm in the UK hence dd/MM/yyyy, yours may show differently)
// your input string
string green = "2017-01-10T13:19:00-07:00";
// parse to a DateTimeOffset
DateTimeOffset dto = DateTimeOffset.Parse(green);
// find the time zone that you are interested in.
// note that this one is US Eastern time - inclusive of both EST and EDT, despite the name.
TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
// convert the DateTimeOffset to the time zone
DateTimeOffset eastern = TimeZoneInfo.ConvertTime(dto, tzi);
// If you need it, you can get just the DateTime portion. (Its .Kind will be Unspecified)
DateTime dtEastern = eastern.DateTime;
When your application needs to be unambiguously aware of timezones, you may want to consider a DateTimeOffset instead of DateTime.
Choosing Between DateTime, DateTimeOffset, TimeSpan, and TimeZoneInfo
And this question looks like someone has collected lots of best practices on this topoic - Daylight saving time and time zone best practices

timespan to datetime conversion format issue to display datetime chart

I am developing windows forms application and has to display datetime line chart with real time data for every one second.
I have to display time on x-axis in the format of (days:hours:min:sec). The time should be 00:00:00:00, 00:00:00:01, 00:00:00:02 etc.
I am taking first response time(system time) as reference time date1. Again after 1 sec, sending request, getting response, capturing system time as date2 and continuously doing like this. I am getting response timespan by subtracting date2 and date1.
But for datetime chart the x-axis only accepts datetime type variable and has to convert to double using ToOADate().
Problem: While converting timespan 00:00:06.2867597 to datetime variable it is converting as 7/25/2016 12:00:06 AM . But I need the fomat 00:00:06
instead of 12:00:06 AM.
Then only using ToOADate(), I will get the correct double value.
Please solve my problem.
Here is my code:
DateTime date1 = DateTime.Now; // {7/25/2016 8:13:29 PM}
DateTime date2 = DateTime.Now; // {7/25/2016 8:13:30 PM}
TimeSpan time = date2 .Subtract(date1); // {00:00:01.3922821}
DateTime logTime = Convert.ToDateTime(time.ToString()); // {7/25/2016 12:00:01 AM}
But I need logTime value should be "00:00:01".
When you are using the DateTime then it will automatically show as your system DateTime format. You have to take it as string for desire output this way
string logTime = Convert.ToDateTime(time.ToString()).ToString("MM/dd/yyyy HH:mm:ss");
if you want only time part then
string logTime = Convert.ToDateTime(time.ToString()).ToString("HH:mm:ss");
To display your logTime as a 24-hour string:
logTime.ToString("HH:mm:ss");
You can't change the logTime DateTime value itself to represent 00:00:01, because they are the same value, you're just changing how you display it.

Convert datetime entered by user to UTC

The user enters a date and a time in separate textboxes. I then combine the date and time into a datetime. I need to convert this datetime to UTC to save it in the database. I have the user's time zone id saved in the database (they select it when they register). First, I tried the following:
string userTimeZoneID = "sometimezone"; // Retrieved from database
TimeZoneInfo userTimeZone = TimeZoneInfo.FindSystemTimeZoneById(userTimeZoneID);
DateTime dateOnly = someDate;
DateTime timeOnly = someTime;
DateTime combinedDateTime = dateOnly.Add(timeOnly.TimeOfDay);
DateTime convertedTime = TimeZoneInfo.ConvertTimeToUtc(combinedDateTime, userTimeZone);
This resulted in an exception:
The conversion could not be completed because the supplied DateTime did not have the Kind property set correctly. For example, when the Kind property is DateTimeKind.Local, the source time zone must be TimeZoneInfo.Local
I then tried setting the Kind property like so:
DateTime.SpecifyKind(combinedDateTime, DateTimeKind.Local);
This didn't work, so I tried:
DateTime.SpecifyKind(combinedDateTime, DateTimeKind.Unspecified);
This didn't work either. Can anyone explain what I need to do? Am I even going about this the correct way? Should I be using DateTimeOffset?
Just like all the other methods on DateTime, SpecifyKind doesn't change an existing value - it returns a new value. You need:
combinedDateTime = DateTime.SpecifyKind(combinedDateTime,
DateTimeKind.Unspecified);
Personally I'd recommend using Noda Time which makes this kind of thing rather clearer in my rather biased view (I'm the main author). You'd end up with this code instead:
DateTimeZone zone = ...;
LocalDate date = ...;
LocalTime time = ...;
LocalDateTime combined = date + time;
ZonedDateTime zoned = combined.InZoneLeniently(zone);
// You can now get the "Instant", or convert to UTC, or whatever...
The "leniently" part is because when you convert local times to a specific zone, there's the possibility for the local value being invalid or ambiguous in the time zone due to DST changes.
You can also try this
var combinedLocalTime = new DateTime((dateOnly + timeOnly.TimeOfDay).Ticks,DateTimeKind.Local);
var utcTime = combinedLocalTime.ToUniversalTime();

How to get yesterday's date in C#

I want to retrieve yesterday's date in my ASP.NET web application using C#.
I've tried searching for a solution but have not had much success. The code I'm using just outputs today's date:
string yr = DateTime.Today.Year.ToString();
string mn = DateTime.Today.Month.ToString();
string dt = DateTime.Today.Day.ToString();
date = string.Format("{0}-{1}-{2}", yr, mn, dt);
How can I get yesterday's date?
Use DateTime.AddDays() method with value of -1
var yesterday = DateTime.Today.AddDays(-1);
That will give you : {6/28/2012 12:00:00 AM}
You can also use
DateTime.Now.AddDays(-1)
That will give you previous date with the current time e.g. {6/28/2012 10:30:32 AM}
The code you posted is wrong.
You shouldn't make multiple calls to DateTime.Today. If you happen to run that code just as the date changes you could get completely wrong results. For example if you ran it on December 31st 2011 you might get "2011-1-1".
Use a single call to DateTime.Today then use ToString with an appropriate format string to format the date as you desire.
string result = DateTime.Today.AddDays(-1).ToString("yyyy-MM-dd");
You don't need to call DateTime.Today multiple times, just use it single time and format the date object in your desire format.. like that
string result = DateTime.Now.Date.AddDays(-1).ToString("yyyy-MM-dd");
OR
string result = DateTime.Today.AddDays(-1).ToString("yyyy-MM-dd");
You will get yesterday date by this following code snippet.
DateTime dtYesterday = DateTime.Now.Date.AddDays(-1);
var yesterday = DateTime.Now.AddDays(-1);
Something like this should work
var yesterday = DateTime.Now.Date.AddDays(-1);
DateTime.Now gives you the current date and time.
If your looking to remove the the time element then adding .Date constrains it to the date only ie time is 00:00:00.
Finally .AddDays(-1) removes 1 day to give you yesterday.
string result = DateTime.Now.Date.AddDays(-1).ToString("yyyy-MM-dd");
DateTime dateTime = DateTime.Now ;
string today = dateTime.DayOfWeek.ToString();
string yesterday = dateTime.AddDays(-1).DayOfWeek.ToString(); //Fetch day i.e. Mon, Tues
string result = dateTime.AddDays(-1).ToString("yyyy-MM-dd");
The above snippet will work. It is also advisable to make single instance of DateTime.Now;
DateTime.Today as it implies is todays date and you need to get the Date a day before so you subtract one day using AddDays(-1);
There are sufficient options available in DateTime to get the formatting like ToShortDateString depending on your culture and you have no need to concatenate them individually.
Also you can have a desirable format in the .ToString() version of the DateTime instance

Categories

Resources