Date separator issue - c#

I have the following code
DateTime.Now.ToString("MM/dd/yyyy")
It always gives me this output : "04.13.2011" instead of "04/13/2011". May I know why I am getting this weird issue?

You're almost certainly in a culture where that's the default date separator. If you want to force / you can quote it in the format string:
string x = DateTime.Now.ToString("MM'/'dd'/'yyyy")

Try this
DateTime.Now.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture)

Use following code:
DateTime.Now.ToString("MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture)
This ensures that the underlying date and time values do not change when the data is read or written by users from different cultures.

Related

DateTime.ToString() not working as expected

In the screenshot DateTime.ToString() method is being called but the date is not getting formatted in expected format (as seen in Quick Watch widnow). Is something wrong ?
You are using / as separator in your ToString format. But your current culture seems to has - as date separator. That is why you see the difference. You can pass CultureInfo.InvariantCulture with ToString.
Like:
DateTimeObject.ToString("MM/dd/yyy HHmmss", CultureInfo.InvariantCulture)
DateTime.ToString replaces / with the current date separator and : with the current time separator. You're passing in the format yourself, and it does not match what's in the Region settings.
To use the Region settings, use ToShortDateString() and ToShortTimeString().
You can use this:
DateTime.now.ToString("yyyyMMddHHmmss");
or
DateTime.now.ToString("mm-dd-yyyy");

Is a DateTime.ToString format expression affected by the current culture locale?

I have some code that is logging a timestamp in format from a thick client app
DateTime.UtcNow.ToString("MM/dd/yy HH:mm:ss")
Now, on a client running in China (not sure exactly which locale) this is producing a date in the log with the format
11-20-13 02:14:03
I notice it's using - instead of / to delimit the parts, even though I explicitly wanted /
I tried to set the current culture to Chinese simplified zh-CN but I wasn't able to reproduce how the remote client was able to produce that string
Does current culture locale affect the output of this format string? Or does / have some other meaning I'm not aware of?
Yes, the / character is a placeholder for whatever the current culture uses to separate parts of the date. From MSDN:
The "/" custom format specifier represents the date separator, which is used to differentiate years, months, and days. The appropriate localized date separator is retrieved from the DateTimeFormatInfo.DateSeparator property of the current or specified culture.
As with other format specifiers, you can escape the / with a \:
DateTime.UtcNow.ToString(#"MM\/dd\/yy HH\:mm\:ss")
Or specify an explicit culture when formatting the string:
DateTime.UtcNow.ToString("MM/dd/yy HH:mm:ss", CultureInfo.InvariantCulture)
Yes, that's how it works. / is being replaced with the local date separator. The same applies to : as a time separator. You can find more on MSDN: Custom Date and Time Format Strings.
To change that, escape them with \:
DateTime.UtcNow.ToString(#"MM\/dd\/yy HH\:mm\:ss")

String Parsing a Time

I need to obtain a time in the format of "07:30 am" (not case-sensitive). I'm reading a file which has this in the format "07:30am". Eventually I will be constructing a DateTime from this, so I just need to get this back with a space before the am/pm part.
I can detect the occurrence of the a or p using this:
if(startString.IndexOfAny("ap".ToCharArray()) != -1)
{
}
What's the best ways to do this? I'm guessing I will end up with two strings that can be concatenated with a space? Can Split be used with the above snippet to achieve this?
UPDATE:
I need to end up with a space in the DateTime between the minutes and the AM/PM and I do not want to use regular expressions. So far, nothing I've tried here gives me that...
The actual input I have to handle is in this format:
RecDate: "04/30/2012"
RecTime: "05:30am"
I need to create a new DateTime object from these with a space before the am/pm part.
You have two easy choices:
Use RegEx to fix the formatting:
string newTime = Regex.Replace(startString, #"(?<=[01]\d:[0-5]\d)(?=[ap]m)", " ");
Use DateTime.ParseExact to just import the time as-is:
DateTime newValue = DateTime.ParseExact(
startString,
"hh:mmtt",
CultureInfo.InvariantCulture);
I'm partial to the second approach.
You need to use the Invariant Culture because there is no separator defined between the mm and tt in the format.
Why you are not using Regular Expression for this? ( http://msdn.microsoft.com/de-de/library/system.text.regularexpressions.regex(v=vs.80).aspx ) should be an easy thing for a Regex-Wizard (which I'm not)

C# date formatting is losing slash separators

If I do this in C#:
Console.WriteLine(DateTime.Now.ToString("ddd M/dd/yy"));
I would expect output like this:
Wed 6/15/11
But it actually outputs this:
Wed 6 15 11
Why are the slashes disappearing? Is there a way to prevent this and have the date outputted in the expected format?
Console.WriteLine(DateTime.Now.ToString("ddd M/dd/yy", CultureInfo.InvariantCulture));
Console.ReadLine();
try the above
You could also use
Console.WriteLine(dateTime.ToString("ddd M'/'dd'/'yy"));
That's a possible solution if you're not using the invariant culture as mentioned in other answers here.
The default behavior of the "/" (slash) in a format argument is to use the current's culture date separator.
To force the "/" (slash), you must precede it with a "\" (backslash).
Ex.: "yyyy\\/MM\\/dd" will always display a date like "2015/07/02" independent of the current culture in use.

DotNet DateTime.ToString strange results

Why does:
DateTime.Now.ToString("M")
not return the month number? Instead it returns the full month name with the day on it.
Apparently, this is because "M" is also a standard code for the MonthDayPattern. I don't want this...I want to get the month number using "M". Is there a way to turn this off?
According to MSDN, you can use either "%M", "M " or " M" (note: the last two will also include the space in the result) to force M being parsed as the number of month format.
What's happening here is a conflict between standard DateTime format strings and custom format specifiers. The value "M" is ambiguous in that it is both a standard and custom format specifier. The DateTime implementation will choose a standard formatter over a customer formatter in the case of a conflict, hence it is winning here.
The easiest way to remove the ambiguity is to prefix the M with the % char. This char is way of saying the following should be interpreted as a custom formatter
DateTime.Now.ToString("%M");
Why not use
DateTime.Now.Month?
You can also use System.DateTime.Now.Month.ToString(); to accomplish the same thing
You can put an empty string literal in the format to make it a composite format:
DateTime.Now.ToString("''M")
It's worth mentioning that the % prefix is required for any single-character format string when using the DateTime.ToString(string) method, even if that string does not represent one of the built-in format string patterns; I came across this issue when attempting to retrieve the current hour. For example, the code snippet:
DateTime.Now.ToString("h")
will throw a FormatException. Changing the above to:
DateTime.Now.ToString("%h")
gives the current date's hour.
I can only assume the method is looking at the format string's length and deciding whether it represents a built-in or custom format string.

Categories

Resources