Proper date formatting of string read from a SqlDataReader - c#

I'm reading a Date field from a SqlDataReader and I want to write it to a label.
My code for this line looks like this:
lblTDate.Text = string.Format("{0:D}", (DT2(["TDate"].ToString()));
The label shows, for instance, "4/7/2016 12:00:00 AM" but I want it to show "Sunday, April 07, 2016".
I read on this site that using {0:D} should do it, but it's not working.
The field in the SQL Server table is a Date field, not a DateTime field, which makes it all the more baffling that the time is showing up. But, anyway, how can I get my label to show the date in the format I want to see?

Try this:
lblTDate.Text = Convert.ToDateTime(DT2["TDate"]).ToString("dddd, MMMM dd, yyyy", System.Globalization.CultureInfo.InvariantCulture);

You don't want to convert the object that is returned from the indexer to a string, before you hand it off to a String.Format. By leaving out the ToString call you would have got what you want.
lblTDate.Text = string.Format("{0:D}", DT2["TDate"]);
This enables the String.Format implementation to use IFormattable implementation of the DateTime type which makes that the format string you've found will work. Once it is a string there is no way for the String.Format implementation to know what to do.
Alternatively cast the value to the IFormattable interface, like so:
var fmt = DT2["creationdate"] as IFormattable;
if (fmt != null)
{
lblTDate.Text = fmt.ToString(
"dddd, MMMM dd, yyyy",
System.Globalization.CultureInfo.InvariantCulture);
}
but then you have to provide an IFormatProvider implementation, often in the form of an instance of a CultureInfo class.
Notice that in both of the above options, you don't have to to convert the value to a DateTime first.

CultureInfo culture = new CultureInfo("en-Us");
DateTimeFormatInfo dtfi = culture.DateTimeFormat;
var myDate = new DateTime(2016, 7, 4, 12, 0, 0);
string month = culture.TextInfo.ToTitleCase(dtfi.GetMonthName(myDate.Month));
string dayOfWeek = culture.TextInfo.ToTitleCase(dtfi.GetDayName(myDate.DayOfWeek));
string fullDate = $"{dayOfWeek}, {month} {myDate.Day}, {myDate.Year}";
Console.Write(fullDate);

Related

What's the purpose of the format provider in ParseExact() of DateTime and DateTimeOffset?

Let us consider DateTimeOffset.ParseExact
public static DateTime ParseExact (
string s,
string format,
IFormatProvider? provider,
System.Globalization.DateTimeStyles style
);
The expected format is already described via the format parameter, so what's the purpose of the providerparameter? Can anyone please give an example how different provider values can lead to different results?
The meaning of various elements of a custom datetime format string depend on the format provider.
Example:
var aString = "12 avr. 2021";
var gbCulture = new CultureInfo("en-GB");
var frCulture = new CultureInfo("fr-FR");
var canParseGb =
DateTime.TryParseExact(aString, "dd MMM yyyy", gbCulture, DateTimeStyles.None, out var gbDateTime);
var canParseFr =
DateTime.TryParseExact(aString, "dd MMM yyyy", frCulture, DateTimeStyles.None, out var frDateTime);
Same input string s, same format string format, different providers => different results.
For example CultureInfo implements IFormatProvider. So you can pass a culture which has it's own formatting rules apart from your provided format string.
Also note that the format string can contain specifiers that will behave differently with different cultures/format-providers like the "/" custom format specifier:
CultureInfo deCulture = new CultureInfo("de-DE"); // german
CultureInfo frCulture = new CultureInfo("fr-FR"); // french
// works because / is replaced with the passed culture's date-separator which is . in germany
DateTime dateDe = DateTime.ParseExact("25.02.2021", "dd/MM/yyyy", deCulture, DateTimeStyles.None);
// works not since french use / as date-separator
DateTime dateFr = DateTime.ParseExact("25.02.2021", "dd/MM/yyyy", frCulture, DateTimeStyles.None);
As Magnetron has commented the same applies to the ":" custom time format specifier
Different cultures will use different values for things such as month names and days of the week. Jul might be July to you, but in France it's not. For example:
var frenchDate = DateTimeOffset.ParseExact("1 févr. 2020", "d MMM yyyy",
CultureInfo.GetCultureInfo("fr-FR"));
var englishDate = DateTimeOffset.ParseExact("1 Feb 2020", "d MMM yyyy",
CultureInfo.GetCultureInfo("en-GB"));
All of these details can be seen in the CultureInfo object, for example fr-FR looks like this:
The documentation is quite clear on this:
The particular date and time symbols and strings used in input are defined by the formatProvider parameter...

Convert to DateTime from a string '10-April-2020'

Looking for assistance in converting a date string i receive from a web form, where the format will be something like "10-April-2020". I need to save this into the database in the US date format "yyyy-mm-dd" so that the example date provided would go in as '2020-04-10'.
This is what I have so far, which complains that it is not a valid datetime.
string LicenseExpiry = LicenseExpiry.Text;
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime dateExpires = DateTime.ParseExact(LicenseExpiry, "yyyy-MM-dd", culture);
I have also tried the following which also fails.
DateTime dateExpires;
string LicenseExpiry = LicenseExpiry.Text;
IFormatProvider culture = new CultureInfo("en-US", true);
if (DateTime.TryParseExact(LicenseExpiry, "yyyy-MM-dd", culture, DateTimeStyles.None, out dateExpires))
{
// Do something
}
Can anyone help with either of the attempts to see what went wrong? I am not allowed to change the Ui/Form to do any client side date manipulation either, and so my solution needs to be done in the C# code behind file.
MM means the month number (from 01 through 12)
To parse 10-April-2020, you
need MMMM, see
Custom date and time format strings
The "MMMM" custom format specifier represents the full name of the month

Convert string to mm/dd/yyyy datetime

I'm trying to convert string which comes from textbox, for example in this format '03/24/2014' to DateTime. This is what I'm trying:
CultureInfo us = new CultureInfo("en-US");
dtAssemblyDate = DateTime.ParseExact(txtOperationSignatureDate.Value, "dd/MM/yyyy", us);
or
dtAssemblyDate = DateTime.ParseExact(txtOperationSignatureDate.Value, "dd/MM/yyyy", null);
But no luck and I'm getting exceptions that the value cannot be casted as DateTime. How can I fix this problem?
03/24/2014 isn't a valid date in dd/MM/yyyy format (there are only 12 months in a year1).
Either change your format string to MM/dd/yyyy or use a valid date in your chosen format.
1: Or 13 months in some types of Calendar, but "en-US" uses the 12-month Gregorian calendar.
DateTime myDate = DateTime.ParseExact("24/03/2014", "dd/MM/yyyy",
System.Globalization.CultureInfo.InvariantCulture);
03/24/2014 has the day of the month as the middle component. That might seem strange, but that's how it's done in some parts of the world (mostly Northern America).
Thus, when specifying the format for parsing, you also have to put the day of the month (dd) in the middle:
CultureInfo us = new CultureInfo("en-US");
dtAssemblyDate = DateTime.ParseExact(txtOperationSignatureDate.Value, "MM/dd/yyyy", us);
Obviously, it is not possible to parse a text field that accepts both middle-endian (MM/dd/yyyy) and small-endian (dd/MM/yyyy) dates, because ambiguities like 01/02/2014 cannot be resolved automatically.
If the string is expressed in the format MM/dd/yyyy then
CultureInfo us = new CultureInfo("en-US");
dtAssemblyDate = DateTime.ParseExact(txtOperationSignatureDate.Value, "MM/dd/yyyy", us);
but I prefer to use DateTime.TryParse to avoid surprises...
if(DateTime.TryParse(txtOperationSignatureDate.Value,
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dtAssemblyDate))
Console.WriteLine(dtAssemblyDate.ToShortDateString());
CultureInfo us = new CultureInfo("en-US");
DateTime dt = Convert.ToDateTime(txtOperationSignatureDate.Value, us.DateTimeFormat);
Whatever DateTimeFormat you require, you just need to pass corresponding culture with it.
Try using
string date = textbox.Value;
DateTime dt = Convert.ToDateTime(date);

Convert DateTime in C# to yyyy-MM-dd format and Store it to MySql DateTime Field

I am trying to convert DateTime format to yyyy-MM-dd format and store it to DateTime object. But it gives me the System DateTime format that is MM/dd/yyyy.
I am using following code to convert.
string dateTime = DateTime.Now.ToString();
string createddate = Convert.ToDateTime(dateTime).ToString("yyyy-MM-dd h:mm tt");
DateTime dt = DateTime.ParseExact(createddate, "yyyy-MM-dd h:mm tt",CultureInfo.InvariantCulture);
but non of the above line converts into the specified format.
Can any one help to solve this.
I am getting the DateTime from one application and passing this object to other application and That application is storing that date into MySql's DateTime field which is in the format "yyyy-MM-dd".
This is why I have posted this question.
Project 1 has class from that I am getting the date.
and the processor class which is the middle ware of the application it processes the DateTime format to convert in specific format. And passes to the Other project which consumes the DateTime and stores that in the MySql field.
Use DateTime.Now.ToString("yyyy-MM-dd h:mm tt");. See this.
We can use the below its very simple.
Date.ToString("yyyy-MM-dd");
Have you tried?
var isoDateTimeFormat = CultureInfo.InvariantCulture.DateTimeFormat;
// "2013-10-10T22:10:00"
dateValue.ToString(isoDateTimeFormat.SortableDateTimePattern);
// "2013-10-10 22:10:00Z"
dateValue.ToString(isoDateTimeFormat.UniversalSortableDateTimePattern)
Also try using parameters when you store the c# datetime value in the mySql database, this might help.
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"));
I know this is an old thread, but to all newcomers, there's a new simplified syntax (Intellisense highlighted it for me, not sure how new this feature is, but my guess is .NET 5.0)
DateTime date = DateTime.Now;
string createdDate = $"{date:yyyy-MM-dd}";
Maybe doesn't look simplified in this example, but when concatenating a long message, it's really convenient.
GetDateTimeFormats can parse DateTime to different formats.
Example to "yyyy-MM-dd" format.
SomeDate.Value.GetDateTimeFormats()[5]
GetDateTimeFormats
Try this!
DateTime dt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Ticks)
The culture invariant way, best practice:
DateTime.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)

format date in c#

How can I format a date as dd/mm/yyyy or mm/dd/yy ?
Like in VB format("dd/mm/yy",now)
How can I do this in C#?
It's almost the same, simply use the DateTime.ToString() method, e.g:
DateTime.Now.ToString("dd/MM/yy");
Or:
DateTime dt = GetDate(); // GetDate() returns some date
dt.ToString("dd/MM/yy");
In addition, you might want to consider using one of the predefined date/time formats, e.g:
DateTime.Now.ToString("g");
// returns "02/01/2009 9:07 PM" for en-US
// or "01.02.2009 21:07" for de-CH
These ensure that the format will be correct, independent of the current locale settings.
Check the following MSDN pages for more information
DateTime.ToString() method
Standard Date and Time Format Strings
Custom Date and Time Format Strings
Some additional, related information:
If you want to display a date in a specific locale / culture, then there is an overload of the ToString() method that takes an IFormatProvider:
DateTime dt = GetDate();
dt.ToString("g", new CultureInfo("en-US")); // returns "5/26/2009 10:39 PM"
dt.ToString("g", new CultureInfo("de-CH")); // returns "26.05.2009 22:39"
Or alternatively, you can set the CultureInfo of the current thread prior to formatting a date:
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
dt.ToString("g"); // returns "5/26/2009 10:39 PM"
Thread.CurrentThread.CurrentCulture = new CultureInfo("de-CH");
dt.ToString("g"); // returns "26.05.2009 22:39"
string.Format("{0:dd/MM/yyyy}", DateTime.Now)
Look up "format strings" on MSDN to see all formatting options.
Use yy, yyyy, M, MM, MMM, MMMM, d, dd, ddd, dddd for the date component
Use h, hh, H, HH, m, mm, s, ss for the time-of-day component
In you can also write
DateTime aDate = new DateTime();
string s = aDate.ToShortDateString();
for a short notation
or
DateTime aDate = new DateTime();
string s = aDate.ToLongDateString();
for a long notation like "Sunday, Febuary 1, 2009".
Or take a look at MSDN for the possibities of .ToString("???");
Try this :
String.Format("{0:MM/dd/yyyy}", DateTime.Now); // 01/31/2009
String.Format("{0:dd/MM/yyyy}", DateTime.Now); // 31/01/2009
String.Format("{dd/MM/yyyy}", DateTime.Now); // 31/01/2009
Better yet, use just
DateTime.Now.ToString()
or
DateTime.Now.ToString(CultureInfo.CurrentCulture)
to use the format the user prefers.
I ran into the same issue. What I needed to do was add a reference at the top of the class and change the CultureInfo of the thread that is currently executing.
using System.Threading;
string cultureName = "fr-CA";
Thread.CurrentThread.CurrentCulture = new CultureInfo(cultureName);
DateTime theDate = new DateTime(2015, 11, 06);
theDate.ToString("g");
Console.WriteLine(theDate);
All you have to do is change the culture name, for example:
"en-US" = United States
"fr-FR" = French-speaking France
"fr-CA" = French-speaking Canada
etc...
I think this is simple as you can convert to and from any format without any confusion
DateTime.ParseExact(txt.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture).ToString("yyyy/MM/dd"));

Categories