I'm having some trouble displaying the time in this format: HH:mm:ss.
No matter what i try, i never get it in that format.
I want the time in the culture of the Netherlands which is "nl-NL".
This was one of my (although i forgot to keep the count) 1000th try:
CultureInfo ci = new CultureInfo("nl-NL");
string s = DateTime.Now.TimeOfDay.ToString("HH:mm:ss", ci);
What am i doing wrong?
string s = DateTime.Now.ToString("HH:mm:ss");
You need to use the TimeZoneInfo class, here's how to show the current time in the Eastern Standard Time time zone in HH:mm:ss format:
var timeZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
string s = TimeZoneInfo.ConvertTime(DateTime.Now, timeZone).ToString("HH:mm:ss");
To find all the timezones available, you can use
TimeZoneInfo.GetSystemTimeZones();
Looking through the returned value from the above, the Id for the time zone you need (Amsterdam I assume) is called W. Europe Standard Time:
var timeZone = TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time");
string s = TimeZoneInfo.ConvertTime(DateTime.Now, timeZone).ToString("HH:mm:ss");
TimeOfDay is a TimeSpan, which has only one ToString() without parameters.
Use Darin's solution or a sample from MSDN documentation for TimeSpan.ToString()
Related
Probably a super simple solution but I'm clearly missing something.
I have a string object with value "2020/07/29 13:30:00".
How can I parse that into a DateTimeOffset object and make the assumption that the time zone of that parsed time is "GMT Standard Time" for example, or any TimeZoneInfo I wish to specify preferably?
How can I then take that DateTimeOffset, and return its Utc time but to any specified time zone of my choice?
Many thanks
The easiest I could find is something like this.
I couldn't find any methods to parse a DateTimeOffset in a particular given timezone, but you can parse your string as a DateTime (with a Kind of Unspecified, which just acts as a container for the bits of information in the string, without trying to apply timezone knowledge to it).
Then you can ask a TimeZoneInfo for the UTC offset in a given timezone at the given local time, and apply this to the DateTime to create a DateTimeOffset.
Once you've got your DateTimeOffset, you can work with it using its ToOffset method, and TimeZoneInfo.ConvertTime.
string input = "2020/07/29 13:30:00";
var timezone = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
// DateTime.Parse creates a DateTime with Kind == Unspecified
var dateTime = DateTime.Parse(input);
Console.WriteLine(dateTime); // 7/29/2020 1:30:00 PM
// Since Kind == Unspecified, timezone.GetUtcOffset will give us the UTC offset in effect at
// the given local time in timezone
var dateTimeOffset = new DateTimeOffset(dateTime, timezone.GetUtcOffset(dateTime));
Console.WriteLine(dateTimeOffset); // 7/29/2020 1:30:00 PM +01:00
// Convert to UTC
Console.WriteLine(dateTimeOffset.UtcDateTime); // 7/29/2020 12:30:00 PM
Console.WriteLine(dateTimeOffset.ToOffset(TimeSpan.Zero)); // 7/29/2020 12:30:00 PM +00:00
// Convert to another timezone
var cst = TimeZoneInfo.FindSystemTimeZoneById("Central America Standard Time");
Console.WriteLine(TimeZoneInfo.ConvertTime(dateTimeOffset, cst)); // 7/29/2020 6:30:00 AM -06:00
Try the DateTimeOffset.ParseExact overload that accepts a DateTimeStyles parameter.
This code:
var dt=DateTimeOffset.ParseExact("2020/07/29 13:30:00","yyyy/MM/dd HH:mm:ss",
CultureInfo.InvariantCulture,DateTimeStyles.AssumeUniversal);
Returns 2020-07-29T13:30:00.0000000+00:00
There's no GMT Standard Time, that's a very unfortunate name used in Windows that somehow manages to mix up British and UTC time to the point that no-one knows what it means without looking at the docs. This was thoroughly discussed and explained in this question: Difference between UTC and GMT Standard Time in .NET. As one of the answers explains :
The names GMT Standard Time and GMT Daylight Time are unknown outside of Redmond. They are mythical animals that appear only in the bestiary called the Windows Registry.
If you wanted to assume British time and your machine uses a British timezone, you can use DateTimeStyles.AssumeLocal
This function should convert your date time string (with assumption this is GMT Standard Time) to any other timezone:
public static DateTime? ToUTCTimeZone(string sDate, string timeZone)
{
DateTime utcDate = DateTime.Parse(sDate);
DateTimeOffset localServerTime = DateTimeOffset.Now;
utcDate = DateTime.SpecifyKind(utcDate, DateTimeKind.Utc);
TimeZoneInfo cstZone = TimeZoneInfo.FindSystemTimeZoneById(timeZone);
if (cstZone == null)
return null;
return TimeZoneInfo.ConvertTimeFromUtc(utcDate, cstZone);
}//ToUTCTimeZone
I have a date as string. There is no time info.
For eg. "20131031" ie) 31 oktober 2013.
I want to verify whether it is the date on which DST happens or not ?
w.r.t. WesternEurope.
ie) Does c# have an API, to say it is a DST date or not ?
I want simply a boolean as return, for the last sunday of October and last sunday of March.
which are the dates on which clocks are adjusted.
Per MSDN Documentation
Important
Whenever possible, use the TimeZoneInfo class instead of the TimeZone class.
You should consider TimeZone deprecated.
Instead, you can check DST for the local time zone like this:
DateTime dt = new DateTime(2013,10,31);
TimeZoneInfo tzi = TimeZoneInfo.Local;
bool isDST = tzi.IsDaylightSavingTime(dt);
For a specific time zone, do this instead:
DateTime dt = new DateTime(2013,10,31);
TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time");
bool isDST = tzi.IsDaylightSavingTime(dt);
If you want to know when the daylight periods start and stop, you'll have to work through the transition rules from tzi.GetAdjustmentRules(). That can get a bit complex though. You would probably be better off using Noda Time for that.
You can use the TimeZone.IsDaylightSavingTime method, it takes a DateTime:
public virtual bool IsDaylightSavingTime(
DateTime time
)
So for example:
var tz = TimeZone.CurrentTimeZone;
var is_dst = tz.IsDaylightSavingTime(DateTime.Now);
See MSDN for more information.
Yes, there is an API: TimeZone.GetDaylightChanges
http://msdn.microsoft.com/en-us/library/system.timezone.getdaylightchanges.aspx
You provide a year and it will return a DaylightTime object, which contains the start and end dates for daylight saving. You can then compare your date against those two to determine if its a DLS date or not.
Whilst this answer has been accepted, please see Matt Johnson's answer below for details why it's not the best answer and why the TimeZoneInfo class should be used instead. https://stackoverflow.com/a/19523173/7122
I'm up against an issue storing datetimes as UTC and confused why this does not yield the same result when changing timezones:
var dt = DateTime.Parse("1/1/2013");
MessageBox.Show(TimeZoneInfo.ConvertTimeToUtc(dt, TimeZoneInfo.Local).ToString());
I am manually switching my local time zone on the machine between eastern and central.
Central yields 1/1/2013 6:00:00 AM, and Eastern yields 1/1/2013 5:00:00 AM. What am I missing here? They should be the same regardless of the time zone, correct?
Thanks so much in advance!
I think what you are missing is that the DateTime returned by your DateTime.Parse() statement doesn't come with a time zone. It's just a date and time that can be in any time zone. When you call TimeZoneInfo.ConvertTimeToUtc(dt, TimeZoneInfo.Local), you are telling it which time zone it starts in. So if you start in Central, you will get one answer, whereas if you start in Eastern, you will get an answer that is an hour earlier, UTC. Indeed, this is what your code shows.
There is a .ToUniversalTime() method for DateTime class
This is midnight
var dt = DateTime.Parse("1/1/2013");
Midnight in eastern and central is not the same absolute time.
That is the whole purpose of time zones.
You can use NodaTime :
static string LocalTimeToUTC(string timeZone, string localDateTime)
{
var pattern = LocalDateTimePattern.CreateWithInvariantCulture("dd/MM/yyyy HH:mm:ss");
LocalDateTime ldt = pattern.Parse(localDateTime).Value;
ZonedDateTime zdt = ldt.InZoneLeniently(DateTimeZoneProviders.Tzdb[timeZone]);
Instant instant = zdt.ToInstant();
ZonedDateTime utc = instant.InUtc();
string output = utc.ToString("dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
return output;
}
When you have trouble with converting to local time to UTC then just remove the last keyword of index and then convert to UtcDateTime
NewsDate = DateTimeOffset.Parse(data.NewsDate.Remove(data.NewsDate.LastIndexOf("IST"))).UtcDateTime;
I am trying to convert a string of this format:
MM/dd/yyyy HH:mm
The input is from a US database, so, i.e.:
09/20/2010 14:30
I know that my string is always US time but when I display it, I need to translate that into the local time, so that string should be turned into:
09/20/2010 19:30 (for UK for instance)
I tried a few things but nothing seems to give me the correct solution when I run on a US machine vs a UK or Ge machine
I tried:
CompletedDttm = DateTime.ParseExact(value, "MM/dd/yyyy HH:mm", CultureInfo.CurrentCulture);
CompletedDttm = DateTime.ParseExact(value, "MM/dd/yyyy HH:mm", new CultureInfo("en-US"));
They all work locally (US machine) but they don't convert the time to local time on a European machine.
Thanks
Tony
Try this - it converts local time (input in US format) to GMT and then prints in GB/DE format.
var zones = TimeZoneInfo.GetSystemTimeZones(); // retrieve timezone info
string value = "09/20/2010 14:30";
DateTime CompletedDttm = DateTime.ParseExact(value, "MM/dd/yyyy HH:mm",
new CultureInfo("en-US"));
DateTime FinalDttm = TimeZoneInfo.ConvertTime(CompletedDttm,
TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"),
TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time"));
string output = FinalDttm.ToString(new CultureInfo("en-GB"));
FinalDttm = TimeZoneInfo.ConvertTime(CompletedDttm, TimeZoneInfo.Local,
TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time"));
output = FinalDttm.ToString(new CultureInfo("de-DE"));
Output is, in turn:
20/09/2010 19:30:00
20.09.2010 20:30:00
UPDATE: You have to know the timezone of the data (not just that it is "US") as well as the interpreting machine if you want to reliably convert it to anything else. You're not only looking at hours offset, but DST also which varies by location (not all locales abide by it). Eastern is either -4 or -5 depending on the time of year. And if the date is old enough you run into the issue that "summer" dates were changed recently.
Your best course is to ALWAYS store timestamps in UTC. Aside from that, you can just make guesses about the offset.
You should be working with UTC times (the new, slightly different, version of GMT) if you want to be converting to other time zones.
DateTime dt = new DateTime(DateTime.Parse('2010-10-06 19:40').Ticks, DateTimeKind.Local);
dt.AddHours(5);
dt.ToLocalTime();
You could also make use of TimeZoneInfo which will have DST information also.
Unless you specify otherwise, the parse will assume you mean to parse the string into your current timezone. US culture just means the expected format of the string, and has nothing to do with the timezone (for example, in the US it could be EST or it could be PST).
Your string contains no timezone information, so naturally you're going to get your value in whatever the local timezone is. You can either:
Add the timezone info
Change the timezone afterwards
I think it's a display problem, but need more info to be sure. Try displaying the dates in yyyy-MM-dd format in both cases to check if the problem is on parse or display. You can create a custom format info object if you know exactly what you want to accept or display:
public static DateTimeFormatInfo GetISOFormatInfo()
{
DateTimeFormatInfo dtFormat = new DateTimeFormatInfo();
dtFormat.DateSeparator = "-";
dtFormat.TimeSeparator = ":";
dtFormat.ShortDatePattern = "yyyy-MM-dd";
dtFormat.ShortTimePattern = "HH:mm:ss";
return dtFormat;
}
Using a Date without TimeZone information, you will not be able to know the UK time / Canada time etc... since you do not know who (which part of the world) instered that time. Since you specifically said that the time is US time, you can add the time difference for the different parts of the world to display the local time.
You could use string.Split. first with the '/' separator on the whole string. You will get "09" "20" and "2010 14:30" then apply the split 2 more times with ' ' and ':'
When i display my system date using DateTime.Now() function It gives me system date and time and works fine but when i try to run this page on my server
it gives me the DateTime of Server which is outside India But i want to pick up the time of India whenever this page is executed on server.
I know it is possible through Culture Info Class... Any suggestion....
Put:
private static TimeZoneInfo INDIAN_ZONE = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");
as a field.
Then, use:
DateTime indianTime = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, INDIAN_ZONE);
to get the time as needed.
I use this method to Get current datetime from UTC and saving through Entity Framework
Err.Date = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById("India Standard Time"));
Database Value - 2016-06-23 09:51:13.183
The below code works for me:
TimeZoneInfo INDIAN_ZONE = TimeZoneInfo.FindSystemTimeZoneById("Asia/Kolkata");
DateTime indianTime = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, INDIAN_ZONE);
Console.WriteLine(indianTime.ToString("F"));