Convert DateTime - c#

This works:
testDateTime = DateTime.ParseExact("16/10/2010", "dd/MM/yyyy", null);
This does NOT:
string somedate = "16/10/2010";
testDateTime = DateTime.ParseExact(somedate, "dd/MM/yyyy", null);
why??

Both code snippets are absolutely equivalent and should work/not work the same. I suspect that the value of the somedate variable is not what you think it is inside your application. Try debugging.

Both of your examples are equivalent, and should work if your current culture is en-US, but not necessarily in all other cultures.
For example, the following will throw a FormatException because the de-DE culture uses period as a separator (16.10.2010):
System.Threading.Thread.CurrentThread.CurrentCulture =
CultureInfo.CreateSpecificCulture("de-DE");
DateTime testDateTime = DateTime.ParseExact("16/10/2010", "dd/MM/yyyy", null);
In general it's good practice (FxCop will warn about it) to always specify the IFormatProvider parameter when it's available: usually either CultureInfo.CurrentCulture if you're parsing input from the current user; or CultureInfo.InvariantCulture if you're parsing input from an external source.
// For input from the current user (16.10.2010 in Germany)
testDateTime = DateTime.ParseExact("16/10/2010", "dd/MM/yyyy", CultureInfo.CurrentCulture);
// For input from an external source in a defined culture-invariant format
testDateTime = DateTime.ParseExact("16/10/2010", "dd/MM/yyyy", CultureInfo.InvariantCulture);

It worked fine when I tried it... Just copied and pasted it.
Insert a breakpoint, put your pointer over the variable and check the month, day and year member. If they are not rights, show us what you see.
If you are using a print or msgbox to show the value of the variable, maybe you are not suplying a mask/format for the output.

You are trying to change the DateTime format right? You can not do that with a DateTime object. You can change the format only when you display the DateTime object using String.Format: String.Format("{0:d/M/yyyy HH:mm:ss}", dt). (for example or other methods)

Both the things worked for me when I tried. What is the error you are getting?
The ParseExact() uses the second parameter to parse your input string and not to return the value in that format.
EDIT: from Joe's comment below - The output you get will be in "MM/dd/yyyy" format" - the output will be a DateTime type that doesn't have any intrinsic format.

for some reason it would not work for me UNTIL i added this: CultureInfo.InvariantCulture
DateTime.ParseExact(sValue, "dd/MM/yyyy", CultureInfo.InvariantCulture);

Related

DateTime.TryParse() not working with formatted date dd/MM/yyyy

This code returns (min time 1/1/0001 12:00:00 AM) not Date.Time.Now . Try Parse works for MM/dd/yyyy but not dd/MM/yyyy . Any suggestions
Here is code
DateTime start, end;
DateTime.TryParse(EPSDate12.Text, out start);
string TNow = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"); // Works
// string TNow = DateTime.Now.ToString();// works but gives MM/dd/yyyy as expected
DateTime.TryParse(TNow, out end); // No. gives min time (1/1/0001 12:00:00 AM)
Use TryParseExact and supply the format string.
Also examine the return value from TryParseExact to know if it failed or not (it returns a bool)
I see "EPSDate12.Text" which i suspect may be a TextBox: If you're doing this in a UI, make life easy and use a DateTimePicker - you can set the format, the user can type into them just like a textbox, but they don't accept invalid inputs, and all you have to do is get the .Value property which gives you a DateTime
As to why your attempts to parse the string you made don't work, I think it most likely that the date format Parse is using (which is based on the culture settings of the executing thread) is not the same format as the string you prepared using your forced format. Either make sure your forced format is matched to the current culture, or use a culture that matches your forced format, or use [Try]ParseExact to force the format for parsing like you did when creating the string
See https://learn.microsoft.com/en-us/dotnet/api/system.datetime.parse?view=net-5.0#Culture for more info
The datetime value is internally the same. But, ToString() return value, depends on
the local machine culture setup.
Reference article
The default DateTime.ToString() method returns the string
representation of a date and time value using the current culture's
short date and long time pattern. The following example uses the
default DateTime.ToString() method.
For en-US culture(MM/dd/yyyy hh:mm:ss) , it will be in
7/28/2021 11:37:40 AM
If you want to see in en-GB(dd/MM/yyyy hh:mm:ss), you can apply conversion as given below:
var culture = new CultureInfo("en-GB");
MessageBox.Show($"{DateTime.Now.ToString(culture)}");
28/07/2021 11:45:09 AM
you can also specify exact custom format, in which you want to display.
MessageBox.Show($"{DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss tt")}");
28/07/2021 11:45:09 AM
Thanks for suggestions . Yes DateTime.TryParse is not working and it could be format issue
This line of code.
string TNow = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss");
generates
29/07/2021 14:49:03
which looks OK but fails TryParse

DateTime.Parse doesn't use patterns in current CultureInfo(Silverlight)?

I've got following problem.
I set CurrentCulture and CurrentUICulture and use following patterns in them:
ShortDatePattern is dd-MM-yyyy
LongTimePattern is HH.mm.ss.
When I convert dates to string I get 15-01-2008 00.00.00. But when i call DateTime.Parse("15-01-2008 00.00.00") it throws a FormatException. If i set ShortDatePattern to dd-MM-yyyy HH.mm.ss exception is still thrown. Is there any way to force DateTime.Parse to use pattern for time by setting CurrentCulture accordingly.
I know that using Parse overloads or ParseExact might help, but the whole point was to use formatting without refactoring loads of code that is already written and uses DateTime.Parse and ToString all over the place
Additional info: A also tried putting - and . in ' - it was no use. CurrentCulture is based on Swedish.
if you want to format a DateTIme using String.Format() Method you could do something like this below. String.Format DateTime C#
var dt = "15-01-2008 00.00.00";
var dateFrmt = String.Format("{0:dd/MM/yyyy HH:mm:ss}", dt);
Output = "15-01-2008 00.00.00"
if you want to strip the HH:mm:ss out of the DateTime variable for short date you could do the following here is an example will yield ShortDate
DateTime dt = DateTime.Now;
var dateFrmt = String.Format("{0:M/d/yyyy}", dt);
Output = "1/9/2013"
DateTime.ParseExact Method if you choose to go that route

Unable to parse date time in C#

I know such questions are in ton here. Please go through once
I have a string coming from textbox having current date e.g. 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:
Set Default DateTime Format c#
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);

Help converting a string date to a DateTime

I'm using the Ajax control toolkit calendar extender on a textbox with a submit button. Simple.
The debugger shows that the text is properly being transferred to calling method, but this line of conversion code converts textbox text to 1/1/0001 12:00:00 AM. The text box date is this: 4/15/2011
DateTime txtMyDate = Convert.ToDateTime(txtDate.Text);
What am I doing wrong?
You should use the DateTime.Parse() method:
DateTime txtMyDate = DateTime.Parse(txtDate.Text);
As mentioned you can also use DateTime.ParseExact() using a similar syntax as shown:
DateTime txtMyDate = DateTime.ParseExact(txtDate.Text,
[string format],
[IFormatProvider provider]);
Parse vs ParseExact:
Parse() - assumes the data is valid and does its best to fit it into the type, forcing things that seem vaguely ridiculous when a developer has a chance to invoke common sense.
ParseExact() - only allows the exact format specified and will throw on any variation.
Source on Parse vs ParseExact
There are many ways to convert text to a DateTime, try this one:
DateTime txtMyDate =
DateTime.ParseExact(txtDate.Text, "M/d/yyyy", CultureInfo.InvariantCulture);
Edit: forgot the culture info argument
Use DateTime.ParseExact to extract your date value from a formated date string:
DateTime dateValue =
DateTime.ParseExact(stringDateValue, "M/d/yyyy",
CultureInfo.InvariantCulture);
Try
DateTime instance = DateTime.Parse( txtDate.Text ) ;
which is [somewhat] flexible about what it will accept. Alternatively, DateTime.ParseExact() will give you move control over the conversion.

DateTime.Parse, Latvian culture settings

I am sending in a string in dd/MM/yyyy format, which is then being parsed into lv-LV culture as set per the web.config globalization setting.
I am then comparing the date to DateTime.Now to see if it is in the past.
The problem is, DateTime.Parse converts my string to dd.MM.yyyy format, but DateTime.Now has MM.dd.yyyy format, so the comparison always fails.
Why would DateTime.Now be different to the output from DateTime.Parse, on the same thread culture?
Thanks!
(Update) This is the code I am using:
InputText contains input from a form in DD.MM.YYYY format
DateTime date = DateTime.Parse(InputText, CultureInfo.CurrentCulture);
// Check it's not in the past
this.IsValid = (date.CompareTo(DateTime.Now) > 0);
[DateTime.Now] in this context is in MM.DD.YYYY format using lv-LV cultureInfo
[date] is in DD.MM.YYYY format after the DateTime.Parse
A DateTime does not have formatting - it is simply a point in time.
If you are viewing it, that means you are outputting it. Use the correct culture to output the date.
DateTime.ToString has overloads that take a format provider such as a CultureInfo:
string formatted = DateTime.ToString(new CultureInfo("lv-LV"));
If not specified (in code or configuration), the default system culture will be used (or CultureInfo.InvariantCulture, in some cases).
If you just want to compare the 2 dates, you don't need to convert to string first.
DateTime myDate = DateTime.Parse(myDateAsString);//with the correct locale to ensure it's correctly parsed
if (myDate < DateTime.Now)
{
//it's in the past
}

Categories

Resources