Can I get the "YYYY-MM-DD" string in other languages? - c#

I need to show the "YYYY-MM-DD" as a template in a query editor, so the users know how to formate the dates. But because the application is multi-lingual, I thought it would be easier to understand if I'd display this string for each language.
So for German it would have to be: "JJJJ-MM-TT"
Is there a way to get these strings automatically in C#?

I don't believe what you are asking is possible outside of the box, if you check MSDN, you can see that only specific character literals are reserved for the DateTime formatter to be used when interpreting the string. Any other character literal will be included in the final DateTime string as is (assuming that your DateTime was successfully parsed).
You however can introduce extension functions to DateTime/String, that take CultureInfo and pretty much map a string like "JJJJ-MM-TT" to "YYYY-MM-DD", then pass the mapped string to the DateTime formatter.
You can try to provide custom DateTime formatters inside every different CultureInfo you support in your application, but still passing a string like "JJJJ-MM-TT" to the native DateTime formatter will not give you the desired result, without mapping it to the parse-able format.
If your question is just asking about how to show "JJJJ-MM-TT" to the user but still use "YYYY-MM-DD" when parsing the string, then you will just have to introduce a mapping of the different CultureInfo supported in your application and the strings you want to show to the user, then when presenting a query editor, you lookup the CultureInfo and get the desired string. Still there is no out of the box support for this.

Unfortunately, no, there's nothing built-in.
You will have to localize it manually, the same way you localize all the other strings in your application (e.g. by using resource files).

Related

German culture - get double number from JSON with a comma

I have an MVC Web-API application for inner use. I have some pages with forms and numeric fields. I need to install this on a German computer, and the users will be only Germans. In Germany they write "3,5" instead of "3.5" (with a comma).
In IIS configuration the culture is "Invariant culture" and since the computer is German - the localize is "de-DE".
When the users write "3,5" in the field - I can see in firebug that "3,5" is what is sent in JSON, but the server gets it as "35".
Can I handle it on server-side? (I don't want to change the json because I'll need to do it in every field and page)
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public class ItemsController : ApiController, IDisposable
{
[Authorize(Roles = "Admin")]
[HttpPost]
public HttpResponseMessage UpdateItem(ItemViewModel itemVM)
{
// JSON data sent data.NumProp1 = "3,5"
// itemVM.NumProp1 contains "35" instead of "3.5"
}
}
You should not localize your JSON - see http://www.json.org for the spec (which only shows the dot as a separator) and How to localize when JSON-serializing? for a similar question.
I wouldn't recommend trying to read your customized JSON - it may sound like a quick win right now, but in the end you simply aren't using JSON.
You must use CultureInfo.InvariantCulture on all your string formating calls when handling persitence (and JSON exchanges are technically a form of persitence):
Persisting Data
The InvariantCulture property can be used to persist data in a
culture-independent format. This provides a known format that does not
change and that can be used to serialize and deserialize data across
cultures. After the data is deserialized, it can be formatted
appropriately based on the cultural conventions of the current user.
For example, if you choose to persist date and time data in string
form, you can pass the InvariantCulture object to the
DateTime.ToString(String, IFormatProvider) or
DateTimeOffset.ToString(IFormatProvider) method to create the string,
and you can pass the InvariantCulture object to the
DateTime.Parse(String, IFormatProvider) or
DateTimeOffset.Parse(String, IFormatProvider, DateTimeStyles) method
to convert the string back to a date and time value. This technique
ensures that the underlying date and time values do not change when
the data is read or written by users from different cultures.
This applies to all types: numerics, decimals, floats and doubles, date and time etc. Use the invariant culture both when writing and when reading serialized data. Use invariant culture on both sides of a JSON exchange.
BTW, if you'd use the built-in JSON serializers, you'd already get this lunch for free: JsonWriter.cs, JsonReader.cs.
As already said: JSON is a standard, and you should never deviate from the standard. Doing that will make your life miserable.
If the users enter some numbers in a web form, that web form should serialize that in the correct JSON format. I think usually that is done already, if you use the right numeric types in your form, like input type='number', etc. On the server end, you should read it using the InvariantCulture.
This need for a general solution is acknowledged by the W3C, as you can see in the draft W3C HTML JSON form submission.
In addition to the other answers, if you want to just replace the German "," decimal separator with the current culture one, which makes the conversion parse correctly, use:
str = str.Replace(",", System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
You can then convert your string into a numeric value using stuff like Convert.ToInt32

Why date is displayed differently at server and locally?

I am reading data from an API file, which has this format
<DataPoint>
<Amount>38.361</Amount>
<Time>2014-01-02T12:00:00</Time>
</DataPoint>
when I get the time, and print it at my website at visual studio I get 02/01/2014.
However, If I upload it, I get 1/2/2014.
Why the same code produces different results when I use it at my pc, and when I upload it at the server?
And how I can fix that?
ps: I am programming in C# and I am using the object JArray to get the data if this is important
JArray a = JArray.Parse(text);
But it
That's because of the DateTime CULTURE info. British dates are arranged as dd/MM/yyyy and American dates are MM/dd/yyyy You could just use Datetime.ToString("dd/MM/yyyy") to convert it to datetime format you want to display.
Format in which numeric and datetime values are transformed into string depends on OS culture settings, when you don't set them explicitly in code. Looks like that's the case here.
If you need the same date/numeric format everywhere, no matter how user set's the OS preferences, you should provide IFormatProvider instance which will provide the formatting and override OS default one.
The most commonly used is CultureInfo.InvariantCulture:
var dateString = myDate.ToString(CultureInfo.InvariantCulture);

get the format of a string date in c#

I have a string date like 'Wednesday, May 15, 2013' when I Parse it o lost the original format, is there a way to know what was the original format date or get it before the final Parse?
No, you'll lose the original format, if will now be a different object type with no care for its original format prior to parsing.
Your best option would be to store the pre-parse format prior to parsing as a different variable.
However if you simply wish to format the date in that original format, see Farhad's answer.
You can use this for getting date in a fromat you wish.
String.Format("{0:D}", DateTime.Now); // Tuseday, May 21, 2013
The DateTime struct does not have a format, it stores all of those values on various properties. When you want to display it you specify which format to use.
Using a format specifier when displaying it will likely do what you want. This mdsn article provides some basic information on format specifiers. The only way you can use the exact format you show there is if you know it ahead of time and have a format specifier for it. If you know you'll want to display strings in that format throughout the program it will be easy, if you get many different formats and want to decide how to display your dt at runtime it will be fairly complicated. I'm sure you could write some code to figure out what it is, but once the DateTime is created it will have no notion of what format the string used to create it was in.

current date format

Is there any way to find the current format of date in the time zone? I am retrieving date in the form of string from database and in case the current datetime format does not match, crash comes, "String was not recognized as valid datetime"
It sounds like what's important isn't the current format of the date as your code understand it, but as it gets it from the database. Why is it in the database as a string to start with? If at all possible you should make it an appropriate date/time related field in the database and make the driver do the conversion.
If that's not possible, you should perform the conversion in your code using a custom date/time format which matches what the server gives you, and in an appropriate culture (quite possibly the invariant one).
The DateTime.Parse method uses the format that is set on the executing thread. See the Thread.CurrentCulture to retrieve the CultureInfo that use used when parsing. The CultureInfo.DateTimeFormat returns the format you are looking for.
If you know the format, you should use the DateTime.ParseExact method to parse the input string with a known format.
Sound like you need to use the DateTime.TryParse-method:
http://msdn.microsoft.com/en-us/library/system.datetime.tryparse.aspx
If you don't know in which format the date is passed and .NET can't figure it out I think your out of luck. You could of cause try to see if you could figure out the format by yourself by using regex.

How can I get the format of a parsed string

DateTime.Parse takes a string and returned the equivalent DateTime.
Is there a way to get the format being used by the parser?
For example, 7/19/2011 would return M/dd/yyyy while 19-7-2011 would return dd-M-yyyy.
DateTime.TryParseExact would work for me if it also returned the format being used.
This is not possible because the mapping between a DateTime format and a particular output is not isomorphic (there is no inverse mapping to a single format for each output) - consider just the case 11-07-2011 - is this dd-MM-yyyy or MM-dd-yyyy?
See http://msdn.microsoft.com/en-us/library/1k1skd40.aspx Specifically the Remarks section.
The best way to get the formats that it looks for is to read the docs.
DateTime.Parse uses the current culture of the current thread.
Thread.CurrentThread.CurrentCulture.DateTimeFormat will give you a readonly instance of DateTimeFormatInfo that you can use to inspect the format.
The property ShortDatePattern is the one you are looking for.
This addresses your question regarding the format being used by the parser but there is no way to get the format after the fact.
Loop through a list of formats that you pass one at a time to DateTime.TryParseExact.
When you finally get a true value then you know exactly which format .Net would use to parse it.

Categories

Resources