Format Localized DateTime C# - c#

I want to format localized date into format. e.g yyyyMMdd OR ddMMyyyy OR MMddyyyy based on system date format. Below is what I have tried and it is working , but need efficient way to do same.
DateTime.Now.ToLocalTime().Date.ToString().Replace("/","").Replace(":","").Replace(" ","").Replace("-","")

You can use the ToString overload(read also):
DateTime.Now.ToLocalTime().ToString("yyyyMMdd")
(why you think you need ToLocalTime here? Now always returns the local time)
cant use .ToString("yyyyMMdd") because i need different result
depending on what my system date format is. if system date time is
dd-MM-yyyy i want ddMMyyyy, if its yyyy-MM-dd then expected result is
yyyyMMdd
Then you either stick with your current approach or use something like this:
DateTime.Now.ToString("d").Replace(DateTimeFormatInfo.CurrentInfo.DateSeparator, "")

Related

How to make datetime.now return date in UK format with c#

I want datetime.now to return the datetime object in UK format. It does so on my local computer but when I upload the code to the server it does it in US format
DateTime doesn't have any format associated with it. Formatting is just for presentation. You can do:
string formattedDate = DateTime.Now.ToString(CultureInfo.CreateSpecificCulture("en-GB"));
Or supply a specific/custom format like:
string formattedDate = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
I want datetime.now to return the datetime object in UK format.
There's no such concept, any more than an int is a value "in hex" or "in decimal". A DateTime is just a DateTime - you can specify the format when you convert it to a string. It's really important to understand the difference between an inherent value, and what it looks like after it's converted to text - very few types are aware of a custom, modifiable format to use when converting themselves - it's either provided externally (as for DateTime, numbers etc) or simply fixed.
Before you convert start hard-coding a UK format though, I would strongly advise you to consider exactly what you're doing:
Ideally, avoid the conversion in the first place. A lot of the time, string conversions are unnecessary and can be problematic.
Is the text going to be consumed by another machine? Use an ISO-8601 standard format.
Is the text going to be consumed by a person? Use their culture rather than some arbitrary one you decide on.
... Or display it in a dedicated control...
You can use the overload of the ToString method: ToString("dd/MM/yyyy"), or: ToString("yy/MMM/dd"), etc. etc.
Read more about it here: https://msdn.microsoft.com/en-us/library/zdtaw1bw%28v=vs.110%29.aspx
Also sounds to me that you might want to configure your (UI-)Culture in the web.config? Then it will always be in the same format regardless of the culture of your US/Japanese/european server culture..
More about that here: https://msdn.microsoft.com/en-us/library/bz9tc508%28v=vs.140%29.aspx
LogDate = DateTime.UtcNow.AddHours(1);

How to check for current culture in my ado.net code?

I am trying to parse a date that is coming from a source as "02/11/2013"
In my application, I set the user's culture to either en-CA or en-FR, with their date format's being "dd/MM/yyyy" or "M/d/yyyy"
If I parse the date, and pass in the format, will this work or does it depend on which format I saved to the database?
if (DateTime.TryParseExact(dateString, Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern, null, System.Globalization.DateTimeStyles.None, out dtResult))
{
dt = dtResult;
}
I can think properly right now so I need some clarification.
Me passing in the format of "dd/MM/yyyy" or "M/d/yyyy", does this format the date no matter what format the source is in, or is it me telling the datetime parse that the source will be in this format so use this?
What I am weary of is that someone is saving to the db in one format, and then a french person wants to read the date and their own format (yes I should be storing in utc).
ADO.NET is strongly typed; there are well known types for storing most data. In the case of dates, that would be DateTime in .NET and datetime in most database systems. If you ever need to worry about culture, then you're already doing it wrong, because you are passing the data around as a string rather than as a DateTime / datetime.
This then renders your concern here redundant:
What I am weary of is that someone is saving to the db in one format, and then a french person wants to read the date and their own format (yes I should be storing in utc).
because a DateTime / datetime has no notion of format - it is simply a date/time value. Any UI presentation / parsing of string data should be completely isolated and specific to the UI. Beyond the UI code you should (when talking about dates/times) be using DateTime / datetime exclusively.
Similarly, when storing an integer you should be using int.
If the date is stored only as "02/11/2013" without any other culture identifying information there is no way for you to know how to properly interpret it! You are absolutely right being worried that somebody with a en-FR culture might save a date to the database as "02/11/2013" meaning the 2nd of November and then somebody with an en-US culture might read that date and interpret it as the 11th of February.
You should only pass the current culture if you know that is relevant, meaning that you know the date string was generated using that culture.
A better approach is to NOT store dates like that in the first place. It's best to store the date in a format that includes timezone as well as format information such as the Internet Date/Time RFC 3339 format.
Or, if you can't, at least make sure to take the date and always convert it to say en-US culture before storing in the database and than pass that culture to the DateTime.Parse when reading from the database.
The .NET XML serialization code for dates can come in handy when serializing/deserializing dates in RFC 3339 format. See this SO post for more info..

C# change date between different formats

I want to know if there's a way to change the date format depending on the users local date format setting. The date I will store in the DB it's YYYY-MM-DD but the users have different formats, like DD-MM-YYYY or DD.MM.YYYY. What is a clean, elegant way to ensure that my application always retrives the date in local date format, and SQL server always receives the date in YYYY-MM-DD to be stored.
in the DB it's YYYY-MM-DD
No. If you do it right the storage in the Db does not have a format. It is stored, for example, as a number.
What is a clean, elegant way to ensure that my application always retrives the date in local date format
Your application receives it as a binary value too. You have to think about format every time it becomes a string.
in local date format
For that you could rely on the machine configuration: datevalue.ToString().
But usually you want to take control: datevalue.ToString(specificCultureInfo)
You should always save the date in a datetime object. To parse a date you can use DateTime.TryParseExcact when you know the date format and TryParse when you want to use your users prefrence. However it whould be nicer to use dedecated date controls to get a date from the user.
A DateTime object doesn't have a format. You're probably talking about the string representation of the date.
You can return the date as a string using the user's respective culture settings by calling DateTime.ToShortDateString()
DateTime date = new DateTime(2012, 01, 01);
string dateStringInCurrentCultureFormat = date.ToShortDateString();

Datetime formats and JSON data in C#

I'm having an issue with date/time formats in ASP.NET/C#. I have my SQL Server database set up with a PostDate field set to a type of "datetime". But it's saving the date in a strange format. I added a new row through a form and I got this as the date/time string:
2012-09-28 14:56:48.910
When it gets parsed by JSON.NET it gets even stranger. I get:
2012-09-28T14:56:48.91
The date and time are obviously correct, but how do I set things so that I can parse the date into a human-friendly way? There isn't really any code to post because the date is being added when the row is inserted. I'd like to format this as "Sept. 28, 2012 2:56 pm". How do I do that? Do I need to format the string before or after it's parsed as JSON?
That's not a "strange" format at all. The second form is ISO-8601; the first is ISO-8601 without the T. Considering the strange formats you can get in JSON, it looks like you've been let off pretty lightly!
Serialization formats aren't meant to be user-friendly, particularly - they're meant to be machine-to-machine formats.
I would hope that JSON.NET would give you a DateTime after parsing; it should only be giving you the ISO-8601 format after you've converted back to JSON.
If you've got a DateTime that you want to format for user consumption, there are all kinds of options with standard and custom format strings. Don't forget that you should respect the culture of the user, as far as possible - so make sure you're taking appropriate steps to either set the thread's current culture to be the user's one, or that you're passing the culture explicitly to DateTime.ToString etc.
You can try it in C#:
.ToString("MMM d yyyy, h:mm tt")

C# DateTime.ParseExact for "2012-09-03T06:35:31Z"

In C# I am trying to convert "2012-09-03T06:35:31Z" into a Datetime:
Date = DateTime.ParseExact( "2012-09-03T06:35:31Z", ???);
I'm not sure how to parse the rest of the function
//using System.Globalization; should be at top
Date = DateTime.ParseExact("2012-09-03T06:35:31Z", "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal)
See the custom date and time format documentation. This is similar to the sortable format, but with a Z on the end.
You don't say whether the format is specified as always being in UTC and indicated with Z.
If that is the case, then
DateTime.ParseExact(
yourDateString, #"yyyy\-MM\-ddTHH:mm:ss\Z",
CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal)
Will do fine.
However, if UTC is not specified by the standard you are working to, the input you have to deal with could also be e.g. 2012-09-03T06:35:31+05:00 or 2012-09-03T06:35:31+0500 depending on the ISO 8601 format in use - Z is a special case within that format for +00:00. If you need to handle that possibility, then you want to first create a DateTimeOffset, and then obtain the equivalent UTC DateTime from it:
DateTimeOffset.ParseExact(yourDateString,
new string[]{#"yyyy\-MM\-ddTHH:mm:sszzz",#"yyyy\-MM\-ddTHH:mm:ss\Z"},
CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal).UtcDateTime
Note that we still use AssumeUniversal. This is because the second format is saying "A Z will appear here", but the method then ignores it, so we have to explicitly have this form interpreted as UTC. With the first format though, the zzz will give the timezone, and hence the AssumeUniversal is ignored. (Or to put it another way, it's assuming universal until told otherwise, and that format does indeed say otherwise).
Looks like you are trying to parse an Xml date. If this is the case I would suggest using the XmlConvert class...
Date = System.Xml.XmlConvert.ToDateTime("2012-09-03T06:35:31Z", XmlDateTimeSerializationMode.Local);
You will need to change the XmlDateTimeSerializationMode to the appropriate value.

Categories

Resources