DateTime formating - c#

I'm using CultureInfo() to get format of DateTime
CultureInfo culture = new CultureInfo(CultureInfo.CurrentCulture.Name);
someDateTime.ToString("d", culture));
How to get custom formats and not to lose separator which comes with CultureInfo()?

According to the documentation for DateTimeFormatInfo.DateSeparator:
If a custom format string includes the "/" format specifier, the DateTime.ToString method displays the value of DateSeparator in place of the "/" in the result string.
So just use a custom date/time format string with slashes, and they will be replaced automatically.
Example:
var someDateTime = new DateTime(1900, 12, 21);
Console.WriteLine(someDateTime.ToString("d/M", new CultureInfo("en-US")));
Console.WriteLine(someDateTime.ToString("d/M", new CultureInfo("nl")));
Console.WriteLine(someDateTime.ToString("yyy/M", new CultureInfo("en-US")));
Console.WriteLine(someDateTime.ToString("yyy/M", new CultureInfo("nl")));
Output:
21/12
21-12
1900/12
1900-12
Just be aware that this probably isn't a great idea. The separator is not the only meaningful difference between cultures' date representations. 5/6 means May 6 to Americans, but it means June 5 to most Europeans (even those which use the same date separator).

You can provide a format when you call ToString on DateTime objects.
e.g.:
someDateTime.ToString("MM-yyyy"); // produces a formatted date like 12-1900
Formatting Info: https://www.c-sharpcorner.com/blogs/date-and-time-format-in-c-sharp-programming1

You can also specify the separator property of the DateTimeFormatInfo object, like so:
DateTime someDateTime = DateTime.Now;
CultureInfo culture = new CultureInfo("en-US");
DateTimeFormatInfo dtfi = culture.DateTimeFormat;
dtfi.DateSeparator = "-";
someDateTime.ToString("d", culture);

Related

How to Convert date into String format to Date format in C#?

I am trying to convert this ("2019-09-09"(yyyy-MM-dd)) string into date format. I am using DateTime.ParseExact method, but it is not giving me the expected output.
string transactionDateFrom = "2019-09-09";
var provider = CultureInfo.InvariantCulture;
var c = DateTime.ParseExact(transactionDateFrom, "yyyy-MM-dd", provider);
But it shows output as (09/09/2019 12:12Am) I just need format like (yyyy-MM-dd) and it must be date format not string.
You should also provide format for ToString or whenever you use that, since right now you only use it for parsing.
You may also just edit the culture the following way:
CultureInfo culture = (CultureInfo) CultureInfo.CurrentCulture.Clone();
culture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd";
culture.DateTimeFormat.LongTimePattern = "yyyy-MM-dd";
You should either use DateTime.TryParseExact or use DateTime.TryParse specifying the appropriate CultureInfo.
(For E.g., the culture of the user.)
You can use DateTime.ParseExact method overloads and you can specify exact format and proper (that uses / as a DateSeparator) culture information.
Also be aware that the Difference between M and MM specifiers.
For single digit month numbers, MM specifier will generate month number with leading zero (like 09) but M specifier won't.
string strDate = "2019-09-28";
DateTime date = DateTime.ParseExact(strDate, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
string Format = date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
OR
string strDate = "2019-9-28";
DateTime date = DateTime.ParseExact(strDate, "yyyy-M-dd", System.Globalization.CultureInfo.InvariantCulture);
string Format = date.ToString("yyyy-M-dd", CultureInfo.InvariantCulture);

Convert english Date with parse exact

I try to convert a english date to an german, but my format is not good.
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
DateTime currentCultureDate = DateTime.Now;
string format = "dd.MM.yyyy HH:mm:ss";
Console.WriteLine("Format: " + format);
Console.WriteLine("Original Date: " + currentCultureDate);
DateTime convertedDate = DateTime.ParseExact(currentCultureDate.ToString(), format, new CultureInfo("de-DE"));
Console.WriteLine("Converted Date: " + convertedDate);
FormatException.....
DateTime.ParseExact is used to create a DateTime from a string. You can pass a DateTimeFormat or CultureInfo which will be used to convert that string to DateTime.
The method does not convert it to a string in another CultureInfo, say de-DE. Therefore you can use DateTime.ToString:
string germanFormat = DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss", new CultureInfo("de-DE"));
You are not doing what you say: Your code actually tries to parse the date in German format:
// This is German format
string format = "dd.MM.yyyy HH:mm:ss";
// This takes a date and parses it using the ABOVE FORMAT - which is German
DateTime convertedDate = DateTime.ParseExact(currentCultureDate.ToString(), format, new CultureInfo("de-DE"));
If you already have a DateTime you want to output in German format, you don't need ParseExact, but ToString:
string german = DateTime.Now.ToString(format, new CultureInfo("de-DE"));
A DateTime itself doesn't have any culture formatting attached. It is just a date and a time. Only when you output a DateTime, it somehow needs to be converted into a string and to do so, culture information is required. So the rule of thumb is:
If you get a string that represents a date and time value, you need to parse it into a DateTime, either using a fixed format and ParseExact or relying on the framework, passing the source culture information to Parse or TryParse.
If you have a DateTime and want to output it, you need to format it using ToString, providing either a fixed format string and culture information, or use ToString only for the current thread's culture.

When setting Culture, can I override the date format to e.g. mm/dd/yyyy?

When I set the CurrentCulture, how can I override the date format that is set?
Example:
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US");
Say I wanted to override the default date format so whenever I output DateTime value it is by default in the format I want.
First of all you need to create an instance of CultureInfo that won't be read only. Then you can create an instance of your DateTimeFormatInfo, configure it appropriately and finally assign it to your CultureInfo object:
var culture = CultureInfo.CreateSpecificCulture("en-US");
//or simply var culture = new CultureInfo("en-US");
var dateformat = new DateTimeFormatInfo();
//then for example:
dateformat.FullDateTimePattern = "dddd, mmmm dd, yyyy h:mm:ss tt";
culture.DateTimeFormat = dateformat;
System.Threading.Thread.CurrentThread.CurrentCulture = culture;
The full specification on how to configure your DateTimeFormatInfo can be found here.
No, you can't, because CultureInfo.GetCultureInfo returns a cached, read-only version.
What you can do is format a DateTime like you normally would, or create your own Culture, inheriting the behavior of your desired culture.
Check out the ToString() method on DateTime:
DateTime thisDate1 = new DateTime(2011, 6, 10);
Console.WriteLine("Today is " + thisDate1.ToString("MMMM dd, yyyy") + ".");
There are many, many ways to format dates with patterns. Here is a reference:
http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
DateTime doesn't have format. Strings have. Sounds like you just need to use DateTime.ToString() method like;
CultureInfo culture = CultureInfo("en-US");
DateTime.ToString("mm\/dd\/yyyy", culture);
Rememer The "/" Custom Format Specifier has a special meaning. If you want only / character, you should escape it. Take a look at my another answer.

convert DateTime to string according to customCultureInfo in G((combination of date and Time) format

I have changed my system date format to Faeroese.
I want to convert DateTime to String according to customCulture with G format (combination of date and Time)
check the below code.
namespace TestDateConvertion
{
class Program
{
static void Main(string[] args)
{
object value = new DateTime(2003,12,23,6,22,30);
DateTime dateTimeValue = (DateTime)value;
CultureInfo customCulture = MySettings.getCustomCulture();
//for getting custom culture in my app
//in custom culture i have changed shortDateFormat according to the user preference.
//value in shortDateFormat = dd/MM/yyyy
string result = string.Format(customCulture, "{0:G}", result);
Console.WriteLine(result);
Console.ReadLine();
}
}
}
but i get the output with sepertators according to system DateTime not with users given format in customCulture,
i even dont find any method overloaded in string.Format() or DateTime.ToString() to do this.
If i pass CultureInfo.InvariantCulture then i cant get output in G format.
try this:
DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0);
Console.WriteLine(date1.ToString("G", DateTimeFormatInfo.InvariantInfo));
// Displays 04/10/2008 06:30:00
Console.WriteLine(date1.ToString("G", CultureInfo.CreateSpecificCulture("en-us")));
// Displays 4/10/2008 6:30:00 AM
Console.WriteLine(date1.ToString("G", CultureInfo.CreateSpecificCulture("nl-BE")));
According to Standard Date and Time Format Strings "G" uses short date format (as you claim to specify). So most likely reason of using local culture separator is covered in The "/" Custom Format Specifier portion of ""Custom Date and Time Format Strings".
Since your "short date format" is "dd/MM/yyyy" than instead of "/" it will use corresponding separator from the culture info (which you are likely picking from default culture).
Escaping with \ is covered in the Using the escape character portion of the same "Custom Date and Time Format Strings" article.
So you want your shortDateFormat = #"dd\/MM\/yyyy" or properly specify DateTimeSeparator in corresponding part of your custom CultureInfo.

How can I get date and time formats based on Culture Info?

What I want is..
If culture is en-US then
string dateFormat="MM/dd/yyyy";
string timeFormat="24.00 hrs";
If culture is en-GB then
string dateFormat="dd/mmyyyy";
string timeFormat="24.00 hrs";
and so on for other countries..
Now how do I get these date and time format values ? What are the standards? Like which all countries use similar date/time formats and which ones don't ?
ok I tried this :-
DateTime myDate = new DateTime();
string us = myDate.ToString(new CultureInfo("en-US"));
string us gets value =1/1/0001 12:00:00 AM
Now how do I extract "dd/mm/yyyy" and "24.00 hrs" out of this...in my Dateformat column in my Table... I want to store STRINGS such as dd/mm/yyyy or mm/dd/yyyy NOT dates..In my TimeFormat column in the table, the values to be stores are STRINGS too, like I need to store either "24:00hrs" or "12:00hrs"
How do I do this now ?
**using ShorTimePattern returns these values as
h:mm tt and HH:mm
If I want to store the values in my DB exactly as "24:00hrs" and "12:00hrs", how do I use these values..h:mm tt and HH:mm
which one is for 24 hr format and which for 12 hr format ?**
ok now there's another problem too...I want the information about Decimal Separator and Thousand Separator too based on the CultureInfo...whats the property for that ?
You can retrieve the format strings from the CultureInfo DateTimeFormat property, which is a DateTimeFormatInfo instance. This in turn has properties like ShortDatePattern and ShortTimePattern, containing the format strings:
CultureInfo us = new CultureInfo("en-US");
string shortUsDateFormatString = us.DateTimeFormat.ShortDatePattern;
string shortUsTimeFormatString = us.DateTimeFormat.ShortTimePattern;
CultureInfo uk = new CultureInfo("en-GB");
string shortUkDateFormatString = uk.DateTimeFormat.ShortDatePattern;
string shortUkTimeFormatString = uk.DateTimeFormat.ShortTimePattern;
If you simply want to format the date/time using the CultureInfo, pass it in as your IFormatter when converting the DateTime to a string, using the ToString method:
string us = myDate.ToString(new CultureInfo("en-US"));
string uk = myDate.ToString(new CultureInfo("en-GB"));
// Try this may help
string us = DateTime.Now.Date.ToString("MM/dd/yyyy",new CultureInfo("en-US"));
or
string us = DateTime.Now.Date.ToString("dd/MM/yyyy",new CultureInfo("en-GB"));
You could take a look at the DateTimeFormat property which contains the culture specific formats.
Use a CultureInfo like this, from MSDN:
// Creates a CultureInfo for German in Germany.
CultureInfo ci = new CultureInfo("de-DE");
// Displays dt, formatted using the CultureInfo
Console.WriteLine(dt.ToString(ci));
More info on MSDN. Here is a link of all different cultures.
Try setting a custom CultureInfo for CurrentCulture and CurrentUICulture:
Globalization.CultureInfo customCulture = new Globalization.CultureInfo("en-US", true);
customCulture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd h:mm tt";
System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;
System.Threading.Thread.CurrentThread.CurrentUICulture = customCulture;
DateTime newDate = System.Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd h:mm tt"));
Culture can be changed for a specific cell in grid view.
<%# DateTime.ParseExact(Eval("contractdate", "{0}"), "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture).ToString("dd/MM/yyyy", System.Globalization.CultureInfo.CurrentCulture) %>
For more detail check the link.
Date Format Issue in Gridview binding with #eval()

Categories

Resources