Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Wednesday, February 22, 2017 11:14 AM
Hi,
I have an environment of Windows 2008 R2 SP1 with the Region and Language\Format set to "German (Germany)" and "Long time" set to HHmmss. I would like to parse a string in the format of "dd.mm.YYYY HHmmss" to a DateTime object but I got an exception of "String was not recognized as a valid DateTime.". Below is my sample code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Globalization;
using System.Threading;
namespace ConsoleApplication2
{
class Program
{
private class State
{
public CultureInfo Result { get; set; }
}
static void Main(string[] args)
{
Thread.CurrentThread.CurrentCulture.ClearCachedData();
var thread = new Thread(
s => ((State)s).Result = Thread.CurrentThread.CurrentCulture);
var state = new State();
thread.Start(state);
thread.Join();
var culture = state.Result;
try
{
string strDate = "22.02.2017 154048";
var oDate = DateTime.Parse(strDate, culture);
Console.WriteLine(oDate.ToUniversalTime());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadKey();
}
}
}
When I inserted the colon to separate the time to "15:40:48", then it was working.
Could someone please take a look and provide an advice?
Thank you,
Thang
All replies (2)
Wednesday, February 22, 2017 3:08 PM âś…Answered
Try the following
CultureInfo culture = CultureInfo.InvariantCulture;
string format = "dd.MM.yyyy HHmmss";
string dateString = "22.02.2017 154048";
DateTime date = DateTime.ParseExact(dateString, format, culture);
System.Console.WriteLine(date);
--Vlad
Vladimir Kirnishni
Friday, February 24, 2017 10:29 AM
Thanks Vlad for your answer.
The input date string is produced based on the current system culture so I need to use the current system culture to parse it back, based on your comments, I had to modify the format as below and it is working:
string format = culture.DateTimeFormat.ShortDatePattern + " " + culture.DateTimeFormat.LongTimePattern;