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

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

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

string to dateTime convention changes the format of the string

My code is like this
DateTime dt = new DateTime();
dt= DateTime.ParseExact("14/09/2017", "dd/MM/yyyy", CultureInfo.InvariantCulture);
I am expecting dt to have a format of dd/MM/yyyy but the output I am getting is in MM/dd/yyyy format.
This is the correct out put I am getting 9/14/2017 12:00:00 AM.
Can anyone please point out what I am doing wrong here?
if you expect the format "dd/MM/yyyy" you need to specify it when displaying the DateTime. To do so you can use this overload of the ToString method:
dt.ToString("dd/MM/yyyy");
A DateTime on it's own has no format. Only the string representation of it has one.
EDIT:
Important remark by Tim Schmelter:
/ is a custom format specifier which replaces all occurences with the local date-separator. You either have to esacape them by embedding them within ' or use CultureInfo.InvariantCulture as second parameter. Read this post
That means either use this:
string str_rep = dt.ToString("dd'/'MM'/'yyyy");
or:
string str_rep = dt.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
Your dt is a DateTime, not a string. Format concept only applies when you get their textual (aka string) representation. What you saw is probably what debbuger/ide shows you as a textual representation.
If you get a specific format of your dt, then you can use .ToString() method with dd/MM/yyyy format and a proper culture like InvariantCulture.
string myFormat = dt.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
For beginners, it is really important to understand the difference between what is a DateTime and what is their string representation.
If DateTime.ToString() is resulting in an unexpected format, the likely case is that the current culture isn't being set. By default, the date format used is taken from the host machine. However, you can either specify it directly by setting the thread's CurrentCulture for the culture code you need, or you can set it in your application's configuration file. E.g., a web application's web.config can have a globalization section, like so;
<globalization culture="en-GB" uiCulture="en-GB" />
Alternatively, as already specified, you can set the format explicitly via a custom format string .ToString("dd/MM/yyyy").

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.

Convert DateTime

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);

Format date time

Hey there, I am extracting the date and time of creation of a file. the date should be 7/1/2010 2:08 PM but the format comes out as 2:08:07 01/07/2010 when called from my application. I would like it show as it does in the file explorer (7/1/2010 2:08 PM). How can I accomplish this?
string createdOnCMM = Creationtime; //this returns the 2:08:07 01/07/2010
// I think I need a modified verison of the following to reformat it
DateTime dt = Convert.ToDateTime(createdOnCMM);
String.Format("0:{dd/MM/yyyy HH:mm:ss}", dt);
Your compound format string isn't quite right. Try this:
string s = string.Format("{0:dd/MM/yyyy HH:mm:ss}", dt);
Alternatively, if you only want to format the DateTime, call ToString directly:
string s = dt.ToString("dd/MM/yyyy HH:mm:ss");
(That's a more readable approach, IMO.)
Note that this is very culture-specific at the moment. That may be okay for your intended use, but you should be aware of it.
From Microsoft's Standard Date and Time Format Strings, you should be able to get what you want by using the g format string like the following:
String.Format("{0:g}", dateTimeValue);
That should yield the format you'd like.
If you just need to format with your current culture's short date string then use the g specifier as mentioned in Eric's answer.
If you need the exact format that you mentioned, regardless of your current culture, then one of the following should do the trick:
string formatted = dt.ToString("M'/'d'/'yyyy h':'mm tt");
// or
string formatted = string.Format("{0:M'/'d'/'yyyy h':'mm tt}", dt);

Categories

Resources