I know such questions are in ton here. Please go through once
I have a string
coming from textbox having current date eg 10/9/2012, my class property is of DateTime?
type. I am using Convert.ToDateTime(datetime_string_from_textbox)
but it gives me a FormatException
. I then tried DateTime.ParseExact(string, format, CultureInfo, DateTimeStyle)
as suggested by Jon Skeet here but still it gave me the same exception.
One more thing — my local machine date time format is dd-mm-yyyy
. When I switch this to mm/dd/yyyy
format the code works fine. So basically , I want to know how to parse a valid datetime string to a DateTime
object irrespective of the regional settings, or any settings or any dependency on local machine.
Is this possible?
Update : Code in use
employee.JoiningDate = DateTime.ParseExact(string.Format("{0} 00:00:00", JoiningDate.Text.Trim()), "MM/dd/yyyy hh:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal);
Existing Problem and Required Solution
My system datetime shows 24-10-2012 (that is, 24th Oct) and I have 10/17/2012 in my text box (that is, 17th Oct) since the text box date is also valid and after deployment again the client datetime format will become unknown so, I want a generic way to parse any valid datetime string irrespective of regional settings. Is this possible?
This should work:
var date = DateTime.ParseExact(str, "M/d/yyyy", CultureInfo.InvariantCulture);
As tested bellow:
Try formatting your date to international date format using this method:
How would you format DateTime in international format?
Also you can check this for your current culture:
It totally depends on the machine settings. DateTime.ParseExact(str, "dd/MM/yyyy", CultureInfo.InvariantCulture);
will work for British format but it will give format exception on US format. So use format according to your machine settings.
Try the following if it works
var formatInfo = new DateTimeFormatInfo();
formatInfo.ShortDatePattern = "MM/dd/yyyy";
DateTime.Parse(date, formatInfo);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.