DateTime: how to display as DD.MM.YYYY? - c#

I've got DateTime variable and i want to convert it to string "DD.MM.YYYY"
Please note, the values must be separated by "dot" sign.
Of course I can do manual string composition. But I wonder if I can use DateTime.ToString()
to do required conversion.

Yes, you can:
string formatted = dt.ToString("dd'.'MM'.'yyyy");
Now in this case the quotes aren't actually required, as custom date/time format strings don't interpret dot in any special way. However, I like to make it explicit - if change '.' for ':' for example, then while it's quoted it will stay with the explicit character, but unquoted it would be "the culture-specific time separator". It wasn't entirely obvious to me whether "." would be interpreted as "the culture-specific decimal separator" or not, hence the quoting. You may feel that's over the top, of course - it's entirely your decision.
You may also want to specify the invariant culture, just to remove any other traces of doubt:
string formatted = dt.ToString("dd'.'MM'.'yyyy", CultureInfo.InvariantCulture);
(At that point the quotes around the dot become less relevant, as "." is the decimal separator in the invariant culture anyway.)

Yes, you can use DateTime.ToString like this:
myDateVariable.ToString("dd.MM.yyyy");
Note that you have to use capital MM here, since mm evaluates to minutes instead of months.

Here's an alternative for you:
DateTime.Now.ToString("d", new CultureInfo("de-DE"))
German's use . as the date separator.

You can format the date like this:
date.ToString("dd.MM.yyyy")
When formatting numbers the period . will change depending on the CultureInfo used, but not when formatting dates.
If you are verifying your code against the code analysis rule CA1304: Specify CultureInfo you will have to use the invariant culture even though it doesn't matter for this particular format:
date.ToString("dd.MM.yyyy", CultureInfo.InvariantCulture)

Related

Why does float.Parse("123,45") not throw an exception

... but returns 12345?
The doc for Single.Parse says:
Exceptions
...
FormatException
s does not represent a numeric value.
...
For my understanding "123,45" doesn't represent a proper numeric value (in countries that use comma as thousands separator).
The system's CultureInfo has:
CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator == "."
CultureInfo.CurrentCulture.NumberFormat.NumberGroupSeparator == ","
CultureInfo.CurrentCulture.NumberFormat.NumberGroupSizes == [3]
Apparently the comma is simply ignored and this leads to even more irritating results: "123,45.67" or "1,23,45.67"–which look utterly wrong–become 12345.67.
Supplementary question
I don't get what this sentence in the doc is supposed to mean and whether this is relevant for this case:
If a separator is encountered in the s parameter during a parse operation, and the applicable currency or number decimal and group separators are the same, the parse operation assumes that the separator is a decimal separator rather than a group separator.
In the default and US culture, the comma (,) is legal as a separator between groups. Think of larger numbers like this:
987,654,321
That it's in the wrong place for a group doesn't really matter; the parser isn't that smart. It just ignores the separator.
For the supplemental question, some cultures use commas as the decimal separator, rather than a group separator. This part of the documentation clarifies what will happen if the group separator and decimal separator are somehow set to the same character.
As Joel said, "the parser isn't that smart". The source code is available, so here's the proof.
The code for Single.Parse ends up calling Number.ParseNumber.
Interestingly, Number.ParseNumber is given a NumberFormatInfo object, which does have a NumberGroupSizes property, which defines "the number of digits in each group to the left of the decimal".
However, you'll notice that on line 851, where it checks for the group separator, it doesn't bother to reference the NumberGroupSizes property to check if the group separator is in an expected position. In fact Number.ParseNumber never uses the NumberGroupSizes property.
NumberFormatInfo.NumberGroupSizes is only ever used when converting a number to a string.

How to Allow Characters in Certain Spot in String

I'm trying to parse a date. The problem, is my regular expression omits any letter because I want to avoid 01-28-2019 UTC or any letters outside of the main date. Now, it works fine when the date is formatted like I just listed, however it fails when we get a date formatted like 28-JAN-19.
var sourceValue = Regex.Replace("28-JAN-19", #"[A-Za-z]", "");
var parsed = DateTime.Parse(sourceValue);
The date I need to parse can be in a few different formats. Can a regular expression be used to handle this? If so, what tweaks are needed to trim any letters outside of the xx-xx-xx part of the string?
28-JAN-19
28-01-19
28-JAN-19 13:15:00
28-01-19 13:15:00
28-01-2019 13:15:00
This RegEx should match all the examples you provided:
[0-9]{2}-([A-Za-z]{3}|[0-9]{2})-[0-9]{2,4}( [0-9][0-9]?:[0-9][0-9]?:[0-9][0-9])?
It does make a couple of assumptions though, based on your examples. First, it assumes all your dates will always start with a 2-digit day. It also assumes that your month abbreviations will be 3 letters long. It also assumes that your hours, minutes and seconds will all be 2 digits long. Let me know if any of these assumptions are incorrect.
Here is a fiddle
Regular expressions are likely not your best bet. If you know the full set of formats you might encounter then you can use the regular DateTime.ParseExact with a format string. Check for a FormatException to know if you've successfully parsed the date. If your months are using English abbreviations then be sure to pass in an English culture
DateTime.ParseExact("28-JAN-19", "dd-MMM-yy", new CultureInfo("en"));

How to convert 2.3449 to Decimal

I am trying to convert 2.3449 to Decimal but It converts like 23449,0
I am converting it like below
string temp = "2.3449";
decimal value_ = Convert.ToDecimal(temp);
if I replace the DOT with COLON, it converts it perfectly. But, I dont want to Replace the DOT with COLON in string. What is the good way of converting without replacing.
Your culture treats . as the thousands separator, rather than decimal separator.
You can always use a specific culture:
var val = decimal.Parse(temp, CultureInfo.InvariantCulture);
The same goes for ToString - if you want to print the number with . as the decimal separator, just use the appropriate culture. The local culture (the default) is usually the best bet for anything user-facing, though. Invariant culture is perfect for persistence :)

Regex to validate numbers and forward slashes for date

Hi I am trying to wright Regular Expression for date mm/dd/yyyy C#.
I have this
^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d$
But it doesn't work
How to do so it will works with 3/1/2013 and with 03/01/2013
Don't use regular expressions, use DateTime.TryParse or DateTime.TryParseExact.
Also be aware of the current culture and the user's expectations. Americans use "MM/dd/yyyy" but the rest of the world (generally) uses "dd/MM/yyyy", both are indistinguishable for large ranges of dates.
I agree that you should use DateTime methods for this. But if you want to make the leading zeros optional you can add a ? after them, like so:
^(0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d$

Why string.Format produces such result?

I have a line like the following in my code:
string buffer = string.Format(CultureInfo.InvariantCulture, "{0:N4}", 1008.0);
Why does buffer contain 1,008.0 (note comma) after executing this line?
Yes, I do guess that it's caused by my regional settings. The question is why they affect the result in this case?
EDIT:
Ok, I understand that it's completely my fault. It seems like I should have used F format specifier.
The InvariantCulture is loosely based on en-US which uses , as a thousands (group) separator.
Your result is what I would expect.
I also point you to the details of the N numeric format specifier:
The numeric ("N") format specifier converts a number to a string of the form "-d,ddd,ddd.ddd…", where "-" indicates a negative number symbol if required, "d" indicates a digit (0-9), "," indicates a group separator, and "." indicates a decimal point symbol.
You're using the invariant culture; your culture is irrelevant to this. For this, the N4 format means
-d,ddd,ddd,ddd...
That is, possible leading negative sign indicator and commas between thousands groups. For details see: http://msdn.microsoft.com/en-us/library/dwhawy9k#NFormatString
You can look at
NegativeSign
NumberNegativePattern
NumberGroupSizes
NumberGroupSeparator
NumberDecimalSeparator
NumberDecimalDigits
for the invariant culture. If you do, you'll see:
-
1
{ 3 }
,
.
2
You are getting the comma because of "{0:N4}"
n ----- Number with commas for thousands ----- {0:n}
Source:
You will get the comma even without specifying InvariantCulture
Console.WriteLine(string.Format("{0:n4}", 1008.0));

Categories

Resources