I have the following code that take in input scheduleConfiguration.Time in the UTC and return ticks in local time.
scheduleConfiguration.Time equal {9/13/2015 10:00:00 AM} in UTC
var localTime = scheduleConfiguration.Time.ToLocalTime(); {9/13/2015 1:00:00 PM} in Local
var executionTime = new TimeSpan(localTime.TimeOfDay.Ticks);
I changed my data contract scheduleConfiguration.Time, so I need to use TimeSpan TimeOfDay instead of DateTime Time, but I need to have the same executionTime. So I do next
var local time = DateTime.Now.Date.Add(scheduleConfiguration.TimeOfDay);//{9/13/2015 10:00:00 AM} in Local
var executionTime = new TimeSpan(localTime.Ticks);
So I have the difference in 3 hours (and I have UTC +3 time zone)
How to get the same result as for DateTime in the first situation?
You should use SpecifyKind method.
var time = DateTime.SpecifyKind(DateTime.Now.Date.Add(span), DateTimeKind.Utc);
Console.WriteLine(time.ToLocalTime());
Related
I want to check how it's possible to identify the difference that is more than 12 months from DateTimeOffset.
var startDate = DateTimeOffset.Parse("08/11/2012 12:00:00");
var endDate= DateTimeOffset.Parse("08/12/2013 13:00:00");
TimSpan tt = startDate - endDate;
In the timespan, there is no option for the month or year.
Instead of subtracting one from another to get a TimeSpan, add 12 months to the start to find out the cut-off:
if (startDate.AddMonths(12) > endDate)
{
// ...
}
Note that you should think carefully about corner cases - in particular, what you'd want to do with a start date of February 29th...
You can add or subtract either dates or time intervals from a particular DateTimeOffset value. Arithmetic operations with DateTimeOffset values, unlike those with DateTime values, adjust for differences in time offsets when returning a result. For example, the following code uses DateTime variables to subtract the current local time from the current UTC time. The code then uses DateTimeOffset variables to perform the same operation. The subtraction with DateTime values returns the local time zone's difference from UTC, while the subtraction with DateTimeOffset values returns TimeSpan.Zero.
using System;
public class DateArithmetic
{
public static void Main()
{
DateTime date1, date2;
DateTimeOffset dateOffset1, dateOffset2;
TimeSpan difference;
// Find difference between Date.Now and Date.UtcNow
date1 = DateTime.Now;
date2 = DateTime.UtcNow;
difference = date1 - date2;
Console.WriteLine("{0} - {1} = {2}", date1, date2, difference);
// Find difference between Now and UtcNow using DateTimeOffset
dateOffset1 = DateTimeOffset.Now;
dateOffset2 = DateTimeOffset.UtcNow;
difference = dateOffset1 - dateOffset2;
Console.WriteLine("{0} - {1} = {2}",
dateOffset1, dateOffset2, difference);
// If run in the Pacific Standard time zone on 4/2/2007, the example
// displays the following output to the console:
// 4/2/2007 7:23:57 PM - 4/3/2007 2:23:57 AM = -07:00:00
// 4/2/2007 7:23:57 PM -07:00 - 4/3/2007 2:23:57 AM +00:00 = 00:00:00
}
}
For more details you can read HERE
I have WebApp deployed on US server. I have used DateTime.Now in order to capture User Date and Time on certain Action by the User.
Localy it works fine and gets the Date time correct. But post the deployment function is saving the date time for the Server Date time and not the User.
Users are in India hence it should capture IST and not MST as what it is doing now.
Here is my Code I have used so far with no success:
//Getting the current UTC Time
DateTime UTCTime = System.DateTime.UtcNow;
//Adding the time difference 5.5 hours to the utc time
DateTime IndianTime = UTCTime.AddHours(5.5);
dto.ChatCreateDateTime = IndianTime;
Using TimeZone Class did not work either.
TimeZoneInfo timeZone = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");
DateTime timeUTC = DateTime.UtcNow;
DateTime result = TimeZoneInfo.ConvertTimeFromUtc(timeUTC, timeZone);
dto.ChatCreateDateTime = result;
I did try searching online and tried many fix like TimeZone Class, and other but none worked for me.
Use the below code but no correct datetime. Time shows as behind by 30 mins.
DateTime dateTime = DateTime.Now;
DateTime utcTime = dateTime.ToUniversalTime();
TimeZoneInfo istZone = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");
DateTime yourISTTime = TimeZoneInfo.ConvertTimeFromUtc(utcTime, istZone);
model.ChatCreateDateTime = yourISTTime;
Chat dto = new Chat();
//dto.CustEmail = model.CustEmail;
dto.CustName = model.CustName;
dto.ChatStartDateTime = model.ChatStartDateTime;
// Gets current local date
// Returns 04/09/12 11:30 in my case
dto.ChatStartDateTime = model.ChatStartDateTime;
Thank you in advance.
If you want to convert time from UTC to any specific Time Zone
you should try follwing way.
DateTime dateTime = DateTime.Now; // I am getting date time here
DateTime utcTime = dateTime.ToUniversalTime(); // From current datetime I am retriving UTC time
TimeZoneInfo istZone = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time"); // Now I am Getting `IST` time From `UTC`
DateTime yourISTTime = TimeZoneInfo.ConvertTimeFromUtc(utcTime, istZone); // Finally converting it
var hourIST = yourISTTime.Hour; // More granular extraction.
Output:
Note:
I am trying this way and perfectly working for me. If you require
further modification and granularity you could check our official document here.
I have a variable with date time which I have to set on a specific date by these rukles and scenarios:
The API that I connect to has a daily limit and once that limit is reached I have to wait until NEXT DAY until 9:10 AM CEST <= This is very important
So I've been simply doing this:
var localTime = TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time"));
var tomorrowAt0910 = localTime.AddDays(1).Date + new TimeSpan(9, 10, 0);
And I have realized that this code has a bug, because I can have following scenarios:
Let's say my application would expire on 30th of July at 15:00 PM in which case this logic up there would be VALID
BUT
We have a next following scenario which is more likely to happen:
Application expires on 31st of July 5:00 AM, in which case this logic is faulty because RENEWAL DATE will be set to 1st of August 9:10AM WHICH IS BAD
If the application expires in this second case, I should set the date to same day and few hours difference (from 5AM to 9AM)
How could I do this?
It sounds like what you really want is to say:
Find the current time in Central Europe
Find 9:10am on the same date
If 9:10am is after the current time, add a day
So something like:
// No need to do this more than once
private static readonly TimeZoneInfo centralEuropeZone =
TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time")
private static DateTime GetUtcResetTime()
{
// Using UtcNow to make it clear that the system time zone is irrelevant
var centralEuropeNow = TimeZoneInfo.ConvertTime(DateTime.UtcNow, centralEuropeZone);
var centralEuropeResetTime = centralEuropeNow.Date + new TimeSpan(9, 10, 0);
if (centralEuropeResetTime <= centralEuropeNow)
{
centralEuropeResetTime = centralEuropeResetTime.AddDays(1);
}
return TimeZoneInfo.ConvertTimeToUtc(centralEuropeResetTime, centralEuropeZone);
}
I've made that return a UTC DateTime so that no other code needs to worry about which zone it's in.
Check if the expire date is less that the current date, if so add one day.
DateTime expireDate = new DateTime(2018, 7, 30, 22, 0, 0); //for testing
DateTime tomorrowAt0910 = DateTime.Now.Date.AddHours(9).AddMinutes(10);
if (expireDate.Date < DateTime.Now.Date)
{
tomorrowAt0910.AddDays(1);
}
My software displays date/time using local time and then send it to server in UTC. On the server-side I want to add months, years, weeks, days etc to this date/time. However, the question is, if I use such methods with UTC date/time and then convert it back to local time, would the result be always the same, as if I use this methods with local time directly?
This is an example in C#:
// #1
var utc = DateTime.Now.ToUtcTime();
utc = utc.AddWeeks(2); // or AddDays, AddYears, AddMonths...
var localtime = utc.ToLocalTime();
// #2
var localtime = DateTime.Now;
localtime = localtime.AddWeeks(2); // or AddDays, AddYears, AddMonths...
Would the results in #1 and #2 always be the same? Or timezone can influence the result?
The answer may surprise you but it is NO. You cannot add days, weeks, months, or years to a UTC timestamp, convert it to a local time zone, and expect to have the same result as if you had added directly to the local time.
The reason is that not all local days have 24 hours. Depending on the time zone, the rules for that zone, and whether DST is transitioning in the period in question, some "days" may have 23, 23.5, 24, 24.5 or 25 hours. (If you are trying to be precise, then instead use the term "standard days" to indicate you mean exactly 24 hours.)
As an example, first set your computer to one of the USA time zones that changes for DST, such as Pacific Time or Eastern Time. Then run these examples:
This one covers the 2013 "spring-forward" transition:
DateTime local1 = new DateTime(2013, 3, 10, 0, 0, 0, DateTimeKind.Local);
DateTime local2 = local1.AddDays(1);
DateTime utc1 = local1.ToUniversalTime();
DateTime utc2 = utc1.AddDays(1);
DateTime local3 = utc2.ToLocalTime();
Debug.WriteLine(local2); // 3/11/2013 12:00:00 AM
Debug.WriteLine(local3); // 3/11/2013 1:00:00 AM
And this one covers the 2013 "fall-back" transition:
DateTime local1 = new DateTime(2013, 11, 3, 0, 0, 0, DateTimeKind.Local);
DateTime local2 = local1.AddDays(1);
DateTime utc1 = local1.ToUniversalTime();
DateTime utc2 = utc1.AddDays(1);
DateTime local3 = utc2.ToLocalTime();
Debug.WriteLine(local2); // 11/4/2013 12:00:00 AM
Debug.WriteLine(local3); // 11/3/2013 11:00:00 PM
As you can see in both examples - the result was an hour off, one direction or the other.
A couple of other points:
There is no AddWeeks method. Multiply by 7 and add days instead.
There is no ToUtcTime method. I think you were looking for ToUniversalTime.
Don't call DateTime.Now.ToUniversalTime(). That is redundant since inside .Now it has to take the UTC time and convert to local time anyway. Instead, use DateTime.UtcNow.
If this code is running on a server, you shouldn't be calling .Now or .ToLocalTime or ever working with DateTime that has a Local kind. If you do, then you are introducing the time zone of the server - not of the user. If your users are not in the same time zone, or if you ever deploy your application somewhere else, you will have problems.
If you want to avoid these kind of problems, then look into NodaTime. It's API will prevent you from making common mistakes.
Here's what you should be doing instead:
// on the client
DateTime local = new DateTime(2013, 3, 10, 0, 0, 0, DateTimeKind.Local);
DateTime utc = local.ToUniversalTime();
string zoneId = TimeZoneInfo.Local.Id;
// send both utc time and zone to the server
// ...
// on the server
TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById(zoneId);
DateTime theirTime = TimeZoneInfo.ConvertTimeFromUtc(utc, tzi);
DateTime newDate = theirTime.AddDays(1);
Debug.WriteLine(newDate); // 3/11/2013 12:00:00 AM
And just for good measure, here is how it would look if you used Noda Time instead:
// on the client
LocalDateTime local = new LocalDateTime(2013, 3, 10, 0, 0, 0);
DateTimeZone zone = DateTimeZoneProviders.Tzdb.GetSystemDefault();
ZonedDateTime zdt = local.InZoneStrictly(zone);
// send zdt to server
// ...
// on the server
LocalDateTime newDate = zdt.LocalDateTime.PlusDays(1);
Debug.WriteLine(newDate); // 3/11/2013 12:00:00 AM
I'm storing user time in UTC time and when I show it I need to convert it to am pm time.
Here is example in database I have 17:00:00 convert to 5:00 pm
Here is the code what I came up so far but it's not working
var time = DateTime.ParseExact(object.Time.ToString(), "HHmm", CultureInfo.CurrentCulture).ToString("hh:mm tt");
var time = DateTime.ParseExact("17:00", "HH:mm", null).ToString("hh:mm tt");
returns 05:00 PM
DateTime.ParseExact is returning DateTime
Edited:
Include CultureInfo
var time = DateTime.ParseExact("17:00", "HH:mm", null).ToString("hh:mm tt", CultureInfo.GetCultureInfo("en-US"));
TimeSpan is a duration "17 hours", not a time. Maybe add this to a date (only) and use the existing datetime formatting options? (although watch for daylight savings)
i.e.
string s = DateTime.Today.Add(duration).ToString(specifier);
Don't forget to specify appropriate culture, e.g.: CultureInfo.InvariantCulture.
var time = DateTime.Now.ToString("h:mm tt", CultureInfo.InvariantCulture);
See also: Custom Date and Time Format Strings
I just needed to display static html with my TimeSpan. So in my view I used,
DateTime.Today.Add(StartTime).ToString("%h:mm tt")
"StartTime" is my TimeSpan, it converts it to a DateTime and then displays it. My time now displays as "3:00 PM" instead of "15:00". The "%h" eliminates a leading zero for time that is between 1-9.
Based on your comment, first convert the TimeSpan to a DateTime:
var dtUtc = DateTime.Now.ToUniversalTime();
dtUtc.AddHours(timeSpanObject.Hours);
dtUtc.AddMinutes(timeSpanObject.Minutes);
Once it's a DateTime, you can convert it from UTC to localtime:
var dtLocal = dtUtc.ToLocalTime();
Only when you display it would you include AM/PM, like:
dtLocal.ToString("h:mm tt");