Converting multiple timezone to local time - c#

I'm saving date time in CST timezone,how to change the CST date time to local time.
Ex:
In DB,
Date time is 2013-01-21 06:50:00 and its timezone is CST.This Date Time should be converted into local current time.

Save them as UTC time and then convert them to local time when loading to the UI.

A sample code would be like
using System;
public class Example
{
public static void Main()
{
DateTime date1 = new DateTime(2010, 3, 14, 2, 30, 0, DateTimeKind.Local);
Console.WriteLine("Invalid time: {0}",
TimeZoneInfo.Local.IsInvalidTime(date1));
DateTime utcDate1 = date1.ToUniversalTime();
DateTime date2 = utcDate1.ToLocalTime();
Console.WriteLine("{0} --> {1}", date1, date2);
}
}
// The example displays the following output:
// Invalid time: True
// 3/14/2010 2:30:00 AM --> 3/14/2010 3:30:00 AM
Hope this helps

Related

Unix Timestamp has a UTC difference

I need to convert a Date and Time string to epoch timestamp. I am getting a time difference of 11 hours, (I reckon it is the UTC to local time difference).
using System;
public class Program
{
public static void Main()
{
var output = StringDateToUnixString("08-02-2021 23:59:59", "dd-MM-yyyy HH:mm:ss");
Console.WriteLine($"Result : {output}");
Console.WriteLine("Expected: 1612789199000");
if(output == 1612789199000)
{
Console.WriteLine("Match");
}
else
{
Console.WriteLine("Not a match");
}
}
public static double StringDateToUnixString(string dateString, string currentFormat)
{
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
DateTime date = DateTime.ParseExact(dateString, currentFormat, System.Globalization.CultureInfo.InvariantCulture);
return Convert.ToInt64((date - epoch).TotalMilliseconds);
}
}
When I check, epoch and local are in UTC, however (UTC-UTC).TotalMilliseconds, when converted back is local time.
I really appreciate I can update the StringDateToUnixString function so that the Main can work as expected.
Have you tried this. for get unix timestamp:
DateTimeOffset.Now.ToUnixTimeMilliseconds();
and for convert timestamp to date time:
return new DateTimeOffset(1970, 1, 1, 0, 0, 0, 0, TimeSpan.Zero).AddMilliseconds(1612789199000).UtcDateTime;
The problem is caused because you are subtracting two DateTime values that have different meanings. Your epoch variable is UTC based and has its Kind property set to DateTimeKind.Utc, while your date variable is local-time based and has its Kind property set to DateTimeKind.Unspecified.
However, when subtracting or comparing DateTime values - the Kind property is not considered. The operation is based solely on the Ticks property.
Contrast this with DateTimeOffset values, where the offset is taken into account for such operations.
There are a few different ways you could resolve this in your code, and still adjust from a local-time based date/time string to a Unix Timestamp (which is inherently UTC based):
You could convert the date value to UTC after parsing it, before subtracting:
DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
DateTime dateTime = DateTime.ParseExact(dateString, currentFormat, CultureInfo.InvariantCulture);
return (dateTime.ToUniversalTime() - epoch).TotalMilliseconds;
You could tell DateTime.ParseExact that you'd like a behavior where the input string is assumed to be local time and the output value should be adjusted to UTC. This is done by combining the AssumeLocal and AdjustToUniversal DateTimeStyles flags as follows:
DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
DateTime dateTime = DateTime.ParseExact(dateString, currentFormat, CultureInfo.InvariantCulture,
DateTimeStyles.AssumeLocal | DateTimeStyles.AdjustToUniversal);
return (dateTime - epoch).TotalMilliseconds;
You could parse the value as a DateTimeOffset instead of a DateTime. When doing so, if no offset is in the input string, the local time zone is used. This approach also has the advantage of being able to use the built-in ToUnixTimeMilliseconds method:
DateTimeOffset dateTimeOffset = DateTimeOffset.ParseExact(dateString, currentFormat, CultureInfo.InvariantCulture);
return dateTimeOffset.ToUnixTimeMilliseconds();
Note in all three cases, I assumed using System.Globalization; was included at the top of your program, and that I removed Convert.ToInt64 from the result because it is extraneous.

Calculate datetime from datatimeoffset

I have a datetimeoffset value as 11/22/2016 05:20 AM with an offset of -06:00. I want to get the result as 11/21/2016 11:20 PM after reducing the offset from the time value. I tried
date.UtcDateTime
but it gives me the result as 11/22/206 11:20 PM . What is the way to get the preferred result from datetimeoffset value
The following example shows that when a DateTimeOffset is created, the year, month, day, hour, minute, etc. are interpreted as a local time in the time zone specified by the offset (in udaya726's case, -6 hours). The default output, "11/22/2016 05:20:00 -06:00", should be read as "November 22, 2016, 5:20 AM in the time zone 6 hours behind Greenwich."
using System;
public class StOv4
{
public static void Main()
{
// Time in question: 11/22/2016 05:20 AM with an offset of -06:00
TimeSpan questionOffset = new TimeSpan(-6, 0, 0);
DateTimeOffset questionTime = new DateTimeOffset(2016, 11, 22, 5, 20, 0, 0,
questionOffset);
Console.WriteLine("Time with {0} offset: {1}", questionOffset, questionTime);
// "u" format specifier indicates string is to represent UTC time.
Console.WriteLine("UTC time: {0}", questionTime.ToString("u"));
}
}
Console output:
Time with -06:00:00 offset: 11/22/2016 05:20:00 -06:00
UTC time: 2016-11-22 11:20:00Z

How to set time to midnight for current day?

Every time that I create a non-nullable datetime in my mvc3 application it defaults to now(), where now is current date with current time. I would like to default it to today's date with 12am as the time.
I'm trying to default the time in my mvc...but...the following isn't setting to todays date #12am. Instead it defaults to now with current date and time.
private DateTime _Begin = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 12, 0, 0);
public DateTime Begin { get { return _Begin; } set { _Begin = value; } }
How can I set to 12am for the current date for non-nullable datetime?
You can use the Date property of the DateTime object - eg
DateTime midnight = DateTime.Now.Date;
So your code example becomes
private DateTime _Begin = DateTime.Now.Date;
public DateTime Begin { get { return _Begin; } set { _Begin = value; } }
PS. going back to your original code setting the hours to 12 will give you time of noon for the current day, so instead you could have used 0...
var now = DateTime.Now;
new DateTime(now.Year, now.Month, now.Day, 0, 0, 0);
I believe you are looking for DateTime.Today. The documentation states:
An object that is set to today's date, with the time component set to 00:00:00.
http://msdn.microsoft.com/en-us/library/system.datetime.today.aspx
Your code would be
DateTime _Begin = DateTime.Today;
Using some of the above recommendations, the following function and code is working for search a date range:
Set date with the time component set to 00:00:00
public static DateTime GetDateZeroTime(DateTime date)
{
return new DateTime(date.Year, date.Month, date.Day, 0, 0, 0);
}
Usage
var modifieddatebegin = Tools.Utilities.GetDateZeroTime(form.modifieddatebegin);
var modifieddateend = Tools.Utilities.GetDateZeroTime(form.modifieddateend.AddDays(1));
Only need to set it to
DateTime.Now.Date
Console.WriteLine(DateTime.Now.Date.ToString("yyyy-MM-dd HH:mm:ss"));
Console.Read();
It shows
"2017-04-08 00:00:00"
on my machine.
Related, so I thought I would post for others. If you want to find the UTC of the start of today (for your timezone) the following code works for any UTC offset (-23.5 thru +23.5). This looks like we add X hours then subtract X hours, but the important thing is the ".Date" after the add.
double utcOffset= 10.0; // Set to your UTC offset in hours (eg. Melbourne Australia)
var now = DateTime.UtcNow;
var startOfToday = now.AddHours(utcOffset - 24.0).Date;
startOfToday = startOfToday.AddHours(24.0 - utcOffset);
Most of the suggested solutions can cause a 1 day error depending on the time associated with each date. If you are looking for an integer number of calendar days between to dates, regardless of the time associated with each date, I have found that this works well:
return (dateOne.Value.Date - dateTwo.Value.Date).Days;
Try this:
DateTime Date = DateTime.Now.AddHours(-DateTime.Now.Hour).AddMinutes(-DateTime.Now.Minute)
.AddSeconds(-DateTime.Now.Second);
Output will be like:
07/29/2015 00:00:00

Check if daylight savings is in effect?

How to check if in Denmark daylight time savings has taken effect, if so, then add 1 hour to my data, else not?
I have a xml file:
<day = "1"
month = "5"
sunrise ="06:30"
sunset ="21:30"
/>
Think you need convert this xml to DateTime and then use TimeZoneInfo class.
If Denmark your local time:
DateTime thisTime = DateTime.Now;
bool isDaylight = TimeZoneInfo.Local.IsDaylightSavingTime(thisTime);
Else you need to get Denmark TimeZone:
DateTime thisTime = DateTime.Now;
// get Denmark Standard Time zone - not sure about that
TimeZoneInfo tst = TimeZoneInfo.FindSystemTimeZoneById("Denmark Standard Time");
bool isDaylight = tst.IsDaylightSavingTime(thisTime);
When I coded as above - for New-York, I found in the debugger that the time was set correctly (including DST)
TimeZoneInfo nyTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
DateTime nyTime = GetLocalDateTime(DateTime.UtcNow, nyTimeZone);
if (nyTimeZone.IsDaylightSavingTime(nyTime))
nyTime = nyTime.AddHours(1);
public static DateTime GetLocalDateTime(DateTime utcDateTime, TimeZoneInfo timeZone)
{
utcDateTime = DateTime.SpecifyKind(utcDateTime, DateTimeKind.Utc);
DateTime time = TimeZoneInfo.ConvertTime(utcDateTime, timeZone);
return time;
}
You can use TimeZoneInfo.IsDaylightSavingTime
DateTime theDate = new DateTime(2012, 5, 1); // may 1st
TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
bool isCurrentlyDaylightSavings = tzi.IsDaylightSavingTime(theDate);
Here is a generic test and happy to be corrected if my math is incorrect. In my case I just needed to get the GMT offset for the timezone regardless of where it was in the world.
int timezone;
TimeZoneInfo localZone = TimeZoneInfo.Local;
DateTime myTime = DateTime.Now;
bool isDayLight = TimeZoneInfo.Local.IsDaylightSavingTime(myTime);
if (isDayLight)
timezone = Math.Abs(localZone.BaseUtcOffset.Hours) + 1;
else
timezone = Math.Abs(localZone.BaseUtcOffset.Hours);
Debug.WriteLine("timezone is " + timezone);
I simply found the current time and if it was in Day Light Savings period added +1 to the GMT offset.
This works with Visual Studio Express 2013.
You need to do two things:
call IsAmbiguous
List item IsDaylightSavingTime.
if (TimeZoneInfo.Local.IsAmbiguousTime(unclearDate) ||
TimeZoneInfo.Local.IsDaylightSavingTime(unclearDate))
Console.WriteLine("{0} may be daylight saving time in {1}.", unclearDate, TimeZoneInfo.Local.DisplayName);
https://msdn.microsoft.com/en-us/library/bb460642(v=vs.110).aspx
this is my short solution which can be using in all timezones:
DateTime utcTime = DateTime.Parse("30.10.2018 18:21:34")
DateTime localtime = ConvertUTCToLocalTime(utcTime);
public static DateTime ConvertUTCToLocalTime(DateTime UTCTime)
{
var localZone = TimeZone.CurrentTimeZone;
var offset = localZone.GetUtcOffset(UTCTime);
var localTime = UTCTime.AddHours(offset.Hours);
return localTime;
}
Important
myDateTime.IsDaylightSavingTime DOES return the proper value... but... it is accurate down to at least the hour of the day, just passing the date alone isn't enough.
For instance this year (2019) 3/10/2019 02:00:00 passed as myDateTime will return false, but 3/10/2019 03:00:00 will return true.
Based on other codes provided above, I made a complete code to run and make tests. The variable cityTz is receiving an IANA timezone name example. IANA timezone pattern is used in Mac and Linux (Windows uses different timezone style). In 2020, daylight-saving (DST) in New York ends on November 01. If you test the code below, the return will be FALSE, because "theDate" is November 02, the next day after the end of DST. But if you change the line commented and set theDate to November 01 (last DST date in NY), the return will be TRUE.
You can compile this program in Mac or Linux terminal typing:
csc testDST.cs
To run your program:
mono testDST.exe
Complete code:
using System;
using System.Collections.Generic;
using System.Linq;
class Program{
static void Main(string[] args)
{
string cityTz;
//cityTz = "America/Sao_Paulo";
cityTz = "America/New_York";
//DateTime theDate = new DateTime(2020, 11, 1); //returns TRUE
DateTime theDate = new DateTime(2020, 11, 2); //returns FALSE
Console.WriteLine("Data: "+theDate);
TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById(cityTz);
bool isDaylight = tzi.IsDaylightSavingTime(theDate);
Console.WriteLine("isDaylight this date in "+ cityTz +"?: "+ isDaylight);
}
}

DateTime from user conversion?

I'm getting a time from a use as a string. This time is assumed to be in Eastern time. I need store this in the database as UTC time. How do I do this?
DateTime.SpecifyKind doesn't accept Eastern. In another thread, I read something about using DateTimeOffset
From MSDN:
DateTime easternTime = new DateTime(2007, 01, 02, 12, 16, 00);
string easternZoneId = "Eastern Standard Time";
try
{
TimeZoneInfo easternZone = TimeZoneInfo.FindSystemTimeZoneById(easternZoneId);
Console.WriteLine("The date and time are {0} UTC.",
TimeZoneInfo.ConvertTimeToUtc(easternTime, easternZone));
}
catch (TimeZoneNotFoundException)
{
Console.WriteLine("Unable to find the {0} zone in the registry.",
easternZoneId);
}
catch (InvalidTimeZoneException)
{
Console.WriteLine("Registry data on the {0} zone has been corrupted.",
easternZoneId);
}
http://msdn.microsoft.com/en-us/library/bb397769.aspx
DateTime dateNow = DateTime.Now;
Console.WriteLine("The date and time are {0} UTC.",
TimeZoneInfo.ConvertTimeToUtc(dateNow));

Categories