I'm trying to convert a date in format UTC "yyyy-MM-ddTHH:mmZ" to a localdatetime but when changing cultureInfo by fr-FR or other one, o keep always the same localdatetime
for example i do this:
IFormatProvider culture = new System.Globalization.CultureInfo("en-US",null);
DateTime tempDte= DateTime.MinValue;
string test = ""2014-04-09T14:29Z";
DateTime.TryParseExact(test , "yyyy-MM-ddTHH:mmZ", culture, DateTimeStyles.AssumeLocal, out tempDte)
Console.WriteLine("col = " + s + " &init " + test + " &ToLocalTime = " + tempDte.ToLocalTime() + " &ToUniversalTime = " + tempDte.ToUniversalTime());
Could you explain me how do this for having time depending on th eculture
Thanks
You don't have seconds part in your DateTime String
Try This:
DateTime.TryParseExact(test , "yyyy-MM-ddTHH:mmZ", culture,
DateTimeStyles.AssumeLocal, out validDate);
Note : Make sure you are printing the converted DateTime variable validDate
Related
In application, I'm retrieve time in web service and compare time with time in file XML, I don't know the exact time zone the web service returns so I want to convert both to the same timezone before comparing
-Time in XML file : 2022-05-16T15:37:56.000+07:00
_Time returns in web-service: 2022-05-16 15:30:00
Please help me convert time returns web service to UTC +07
In code compare time:
DateTime date1 = new DateTime(time_XML.Ticks);
DateTime date2 = new DateTime(time_Webservice.Ticks);
int result = DateTime.Compare(date1, date2);
if (result < 0)
{
//relationship = "is earlier than";
return false;
}
else if (result == 0)
{
//relationship = "is the same time as";
return false;
}
else
{
//relationship = "is later than";
return true;
}
You convert a local DateTime to UTC with ToUniversalTime:
DateTime date1 = new DateTime(time_XML.Ticks).ToUniversalTime();
DateTime date2 = new DateTime(time_Webservice.Ticks).ToUniversalTime();
// now compare them
Your example:
string dtStr1 = "2022-05-16T15:37:56.000+07:00";
string dtStr2 = "2022-05-16 15:30:00";
DateTime date1 = DateTime.Parse(dtStr1);
DateTime date2 = DateTime.Parse(dtStr2);
Console.WriteLine("date1: " + date1 + " kind: " + date1.Kind);
Console.WriteLine("date2: " + date2 + " kind: " + date2.Kind);
DateTime dateUtc1 = date1.ToUniversalTime();
DateTime dateUtc2 = date2.ToUniversalTime();
Console.WriteLine("dateUtc1: " + dateUtc1 + " kind: " + dateUtc1.Kind);
Console.WriteLine("dateUtc2: " + dateUtc2 + " kind: " + dateUtc2.Kind);
outputs for me(germany):
date1: 16.05.2022 10:37:56 kind: Local
date2: 16.05.2022 15:30:00 kind: Unspecified
dateUtc1: 16.05.2022 08:37:56 kind: Utc
dateUtc2: 16.05.2022 13:30:00 kind: Utc
I have a date string pulled from Excel which I'm trying to parse. Said date is originally in Gregorian format. Is there any way to retain this even after using TryParse/TryParseExact?
Note: Since our end-users are from Thailand, I'm doing this while my machine's region is set to Thai. Hence, my system date as of this post is "12/7/2561".
Suppose I have the following string input in Gregorian M/d/yyyy format:
string validDate = "7/15/2018"
When I initially tried parsing this using DateTime.TryParseExact, it gave me 15/7/2561.
I've tried the following methods listed in these links, particularly the CreateSpecificCulture:
MSDN: Convert Thailand DateTime TO English DateTime
ASP.NET forums: DateTime issue while converting from thai culture to english culture
Here's my code right now:
public DateTime? ConvertThaiToGregorian(string text, string dateFormat)
{
/// Note: Thailand uses the Thai Buddhist calendar, which is 543 years ahead of
/// the Gregorian calendar.
/// dateFormat here is "M/d/yyyy".
DateTime convertedDate;
// Create Thai CultureInfo
IFormatProvider thCulture = CultureInfo.CreateSpecificCulture("th-TH");
// Parse date = returns "15/7/2018"...
DateTime.TryParseExact(text, dateFormat, thCulture, DateTimeStyles.None, out convertedDate);
// Create en-US CultureInfo
IFormatProvider engCulture = CultureInfo.CreateSpecificCulture("en-US");
// Parse date back to US format = gives me "01/01/0544"...
DateTime.TryParseExact(convertedDate.ToString(), dateFormat, engCulture, DateTimeStyles.None, out convertedDate);
return convertedDate;
}
Any help will be greatly appreciated. Thank you!
Hope it will help you understand how CultureInfo gets the DateTime from a string, the bare minimum requirement is in what culture date string is, but server or operating system shouldn't matter if string is parsed correct. Operating system will interfere only if culture isn't specified when string is parsed.
C# fiddle here: https://dotnetfiddle.net/wdDlts
using System;
using System.Globalization;
public class Program
{
public static void Main()
{
string thaiBudistDate = "12/7/2561";
// US format
CultureInfo provider = CultureInfo.GetCultureInfo("en-US");
DateTime date = DateTime.Parse(thaiBudistDate, provider);
Console.WriteLine("Original string: '" + provider + "' in 'en-US' => Day: " + date.Day + " Month: " + date.Month + " Year: " + date.Year );
// Thai Culture
provider = CultureInfo.GetCultureInfo("th-TH");
date = DateTime.Parse(thaiBudistDate, provider);
Console.WriteLine("Original string: '" + provider + "' in 'th-TH' => Day: " + date.Day + " Month: " + date.Month + " Year: " + date.Year );
// Thai Culture format! M/d/yyyy
provider = CultureInfo.GetCultureInfo("th-TH");
var format = "M/d/yyyy";
date = DateTime.ParseExact(thaiBudistDate, format, provider);
Console.WriteLine("Original string: '" + provider + "' in 'th-TH' format specified 'M/d/yyyy' => Day: " + date.Day + " Month: " + date.Month + " Year: " + date.Year );
// Thai Culture format d/M/yyyy
provider = CultureInfo.GetCultureInfo("th-TH");
format = "d/M/yyyy";
date = DateTime.ParseExact(thaiBudistDate, format, provider);
Console.WriteLine("Original string: '" + provider + "' in 'th-TH' format specified 'd/M/yyyy' => Day: " + date.Day + " Month: " + date.Month + " Year: " + date.Year );
// Using Gregorian time
string usaDate = "12/7/2018";
// US Culture
provider = CultureInfo.GetCultureInfo("en-US");
date = DateTime.Parse(usaDate, provider);
Console.WriteLine("Original string: '" + usaDate + "' in 'en-Us' => Day: " + date.Day + " Month: " + date.Month + " Year: " + date.Year );
// You got the point, dones't matter what provider you use! Hope this will help you undestand how wondows Culture works
usaDate = "12/7/2018";
// Thai Culture
provider = CultureInfo.GetCultureInfo("th-TH");
date = DateTime.Parse(usaDate, provider);
Console.WriteLine("Original string: '" + usaDate + "' in 'th-TH' => Day: " + date.Day + " Month: " + date.Month + " Year: " + date.Year );
}
}
If you already have the datetime converted to Thai culture (where day, month and year properties are correctly set) I think its enough to format it again to Datetime.ToString("M/d/yyyy") in case you want the string representation.
I am unable to convert the string values that has been extracted from the ddl to a DateTime datatype.
The Error Message
An exception of type 'System.FormatException' occurred in mscorlib.dll
but was not handled in user code. Additional information: String was
not recognized as a valid DateTime.
I only require the date to be updated in the SQL database.
This is the an image of the DataDictionary and the Attribute I require would be the birthdate
These are my current codes that get and convert the date time.
string birth = ddlDay.SelectedItem.Value + "-" + ddlMonth.SelectedItem.Value + "-" + ddlYear.SelectedItem.Value;
DateTime birthDate = DateTime.ParseExact(birth, "dd-MMMM-yyyy", System.Globalization.CultureInfo.InvariantCulture);
objCustomer.birthDate = birthDate;
string date = "01/08/2008";
DateTime dt = Convert.ToDateTime(date);
Console.WriteLine("Year: {0}, Month: {1}, Day: {2}", dt.Year, dt.Month, dt.Day);
Instead of ParseExact you could use TryParse to be safe. ie:
var ddlDaySelectedItemValue = "29";
var ddlMonthSelectedItemValue = "Feb"; // February, 2, 02
var ddlYearSelectedItemValue = "2016";
DateTime birthDate;
string birth = ddlYearSelectedItemValue + " " + ddlMonthSelectedItemValue + " " + ddlDaySelectedItemValue;
if (DateTime.TryParse(birth, System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out birthDate))
{
objCustomer.birthDate = birthDate;
}
Change your code to:
DateTime.ParseExact(birth, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture);
I have local time in string format: "yyyy-MM-dd HH:mm:ss" and an IANA Time Zone for that time (e.g. "Europe/London").
How do I convert that in C#, maybe using NodaTime, to a UTC+TimeZone Offset string
e.g. "yyyy-MM-dd HH:mm:ss+01:00" ?
I don't even know where to start!
This is as far as I get (I am afraid I'm new to C sharp):
I understand I need to convert it to an instant, but just can't get to grips with the library.
string dateTime = "2014-12-31 12:30:00";
string IANA = "Europe/London";
Instant instDateTime = NodaTime.Instant.FromDateTimeUtc(Convert.ToDateTime(dateTime));
string outputUTC = string.Format("yyyy-MM-dd HH:mm:ssZ", instDateTime);
Thanks to Matt (see answer below), I now have the functions I needed (Note that in the end what I needed was UTC and not date time + offset):
What is a little worrying is that is says that Europe/Moscow is UTC+04:00, whereas it is actually UTC+03:00 since 26 October 2014.
static void Main(string[] args)
{
string dateTime = "2014-12-31T12:30:00";
string timeZone = "Europe/Moscow";
Console.WriteLine(timeZone + " Local time '" + dateTime + "' to Zulu time");
Console.WriteLine(ConvertIANALocalTimeToZulu(timeZone, dateTime));
Console.WriteLine();
Console.WriteLine("Zulu time '" + dateTime + "' to " + timeZone + " local time");
Console.WriteLine(ConvertZuluTimeToIANALocalTime(timeZone, dateTime));
Console.ReadLine();
}
static string ConvertIANALocalTimeToZulu(string timeZoneIANA, string localDateTime)
{
var pattern = LocalDateTimePattern.CreateWithInvariantCulture("yyyy-MM-ddTHH:mm:ss");
LocalDateTime ldt = pattern.Parse(localDateTime).Value;
ZonedDateTime zdt = ldt.InZoneLeniently(DateTimeZoneProviders.Tzdb[timeZoneIANA]);
Instant instant = zdt.ToInstant();
ZonedDateTime zulu = instant.InUtc();
////string output = zulu.ToString("yyyy-MM-dd HH:mm:sso<m>", CultureInfo.InvariantCulture);
string output = zulu.ToString("yyyy-MM-ddTHH:mm:ss", CultureInfo.InvariantCulture);
return output;
}
static string ConvertZuluTimeToIANALocalTime(string timeZoneIANA, string zuluDateTime)
{
var pattern = InstantPattern.CreateWithInvariantCulture("yyyy-MM-ddTHH:mm:ss");
Instant instant = pattern.Parse(zuluDateTime).Value;
ZonedDateTime zdt = instant.InZone(DateTimeZoneProviders.Tzdb[timeZoneIANA]);
////string output = zdt.ToString("yyyy-MM-dd HH:mm:sso<m>", CultureInfo.InvariantCulture);
string output = zdt.ToString("yyyy-MM-ddTHH:mm:ss", CultureInfo.InvariantCulture);
return output;
}
It's unclear from your question if you meant that the original value was in UTC or in local time.
If it's in UTC, then do the following:
string dateTime = "2014-12-31 12:30:00";
string timeZone = "Europe/London";
var pattern = InstantPattern.CreateWithInvariantCulture("yyyy-MM-dd HH:mm:ss");
Instant instant = pattern.Parse(dateTime).Value;
ZonedDateTime zdt = instant.InZone(DateTimeZoneProviders.Tzdb[timeZone]);
string output = zdt.ToString("yyyy-MM-dd HH:mm:sso<m>", CultureInfo.InvariantCulture);
If it's in local time, then do this instead:
string dateTime = "2014-12-31 12:30:00";
string timeZone = "Europe/London";
var pattern = LocalDateTimePattern.CreateWithInvariantCulture("yyyy-MM-dd HH:mm:ss");
LocalDateTime ldt = pattern.Parse(dateTime).Value;
ZonedDateTime zdt = ldt.InZoneLeniently(DateTimeZoneProviders.Tzdb[timeZone]);
string output = zdt.ToString("yyyy-MM-dd HH:mm:sso<m>", CultureInfo.InvariantCulture);
Also - you should note that in December, London is on GMT (UTC+00:00) - so the output of either function will be "2014-12-31 12:30:00+00:00" for the values you provided.
string strDateFrom;
string strDateTo;
CrystalDecisions.Shared.ParameterDiscreteValue DateValue = new CrystalDecisions.Shared.ParameterDiscreteValue();
if ((strDateFrom != "") && (strDateTo != ""))
{
DateValue.Value = "(From: " + strDateFrom + " - " + strDateTo + ")";
}
else
{
DateValue.Value = "(ALL DATES)";
}
You can use DateTime.Parse
string date = "2020-02-02";
DateTime time = DateTime.Parse(date);
Console.WriteLine(time);
Or use:
DateTime oDate = DateTime.Parse(string s);
If you know the format used, you can try DateTime.ParseExact() or DateTime.TryParseExact():
String text = "30/12/2013";
DateTime result = DateTime.ParseExact(text, "d/M/yyyy", CultureInfo.InvariantCulture);
In order to avoid formatting issue, I prefer using DateTime.ParseExact or DateTime.TryParseExact.
basically the difference between those methods and DateTime.Parse is weather you know the date format of the string (and then you use DateTime.ParseExact) or not (and then use DateTime.Parse).
You can read more about ParseExact and TryParseExact
EDIT:
Example code from the links:
string dateString, format;
DateTime result;
CultureInfo provider = CultureInfo.InvariantCulture;
// Parse date-only value with invariant culture.
dateString = "06/15/2008";
format = "d";
try {
result = DateTime.ParseExact(dateString, format, provider);
Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException) {
Console.WriteLine("{0} is not in the correct format.", dateString);
}
// Parse date-only value without leading zero in month using "d" format.
// Should throw a FormatException because standard short date pattern of
// invariant culture requires two-digit month.
dateString = "6/15/2008";
try {
result = DateTime.ParseExact(dateString, format, provider);
Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException) {
Console.WriteLine("{0} is not in the correct format.", dateString);
}