C# datetime format change - c#

I want to convert datetime.now format which is "dd/mm/yyyy hh:mm:ss AM/PM" to US time format i.e. "mm-dd-yyyy hh:mm:ss AM/PM". More over i want the converted format as datetime not in string because the same is being stored in the database and the field in the database is in datetime format so it will not take string.Please suggest....

A DateTime value doesn't have a format. DateTime.Now doesn't have a format, and if you do any kind of conversion, if you've got a DateTime, there's no format. The concept of a format only applies when you're converting to or from a string - and DateTime.Now is a DateTime, not a string.
Just insert the value into the database using DateTime.Now (or DateTime.UtcNow) and you'll preserve the data which is the important part.
You should only perform string conversions when you actually have to - at which point you can use DateTime.TryParseExact and DateTime.ToString using custom date/time format strings. (Use TryParseExact for user input; for machine input which really should be valid, use DateTime.ParseExact.)
Note that it's usually a good idea to use custom date/time patterns with the invariant culture, or standard date/time patterns with "real" cultures (e.g. the user's culture).

Try this. Standard Date and Time Format Strings
DateTime.Now.ToString("g",CultureInfo.CreateSpecificCulture("en-us"))

DateTime usDateTimeFormat = DateTime.Parse(DateTime.Now ,
System.Globalization.CultureInfo.GetCultureInfo("en-us"));

Related

Inconsistency when parsing DateTime in the same format

I have the following strings:
10/10/2021 00:00:00 and 18/11/2021 23:59:59
I have this code:
bool first = DateTime.TryParse("10/10/2021 00:00:00",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out DateTime firstDate);
bool second = DateTime.TryParse("18/11/2021 23:59:59",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out DateTime secondDate);
Console.WriteLine(firstDate + " --- " + secondDate);
The output is:
10/10/2021 12:00:00 AM --- 1/1/0001 12:00:00 AM
As you can see the second date is not properly parsed, even though it's in the same format. What is the reason for that and how can I fix it?
As you can see the second date is not properly parsed, even though it's in the same format.
Here my two cents.
Programming languages and frameworks are not smart enough to know which kind of format data you applied, specially for dates, times, numbers etc.. If you provide these data, you kinda have to provide the proper format as well so they can do their job. You "said" the same format, but you didn't apply any format in your code. So, as we humans, we know (at least you told us) but the computer don't know.
Let's look what TryParse(String, IFormatProvider, DateTimeStyles, DateTime) documentation says;
Converts the specified string representation of a date and time to its
DateTime equivalent using the specified culture-specific format
information and formatting style, and returns a value that indicates
whether the conversion succeeded.
You didn't supply format information you supplied IFormatProvider as InvariantCulture. So, what are these "culture specific formats"?
Well, most of them are returns with GetAllDateTimePatterns method (but not all of them) but be aware because documentation says;
You can use the custom format strings in the array returned by the
GetAllDateTimePatterns method in formatting operations. However, if
you do, the string representation of a date and time value returned in that formatting operation cannot always be parsed successfully by the
Parse and TryParse methods. Therefore, you cannot assume that the
custom format strings returned by the GetAllDateTimePatterns method
can be used to round-trip date and time values.
So, if you run;
CultureInfo.InvariantCulture.DateTimeFormat.GetAllDateTimePatterns().Dump();
*Dump is just an extension method of LINQPad by the way, it just outputs to the console.
You will get a lot of datetime patterns, but for our case, the important one is we get MM/dd/yyyy HH:mm:ss format for InvariantCulture.
As you can see, your 18/11/2021 23:59:59 data doesn't match with MM/dd/yyyy HH:mm:ss format because there is no 18th month on Gregorian calendar which is a DateTime instance belongs internally.
Your second parsing fails by the way, that's quite different just saying "the second date is not properly parsed" and this is how DateTime.TryParse method works as explained in the documentation;
When this method returns, contains the DateTime value equivalent to
the date and time contained in s, if the conversion succeeded, or
MinValue (which is 1/1/0001 12:00:00 AM) if the conversion failed. The conversion fails if the s
parameter is null, is an empty string (""), or does not contain a
valid string representation of a date and time.
So, best way to handle this to supply a "specific" format using with DateTime.TryParseExact method or one of its overloads like;
bool first = DateTime.TryParseExact("10/10/2021 00:00:00",
"dd/MM/yyyy HH:mm:ss",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out DateTime firstDate);
bool second = DateTime.TryParseExact("18/11/2021 23:59:59",
"dd/MM/yyyy HH:mm:ss",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out DateTime secondDate);
The default DateTime format is 'MM/dd/yyyy' and since you have the date in 'dd/MM/yyyy' format it gives you the output.
Maybe try changing the date format input as 11/18/2021 23:59:59

String with dd/MM/yyyy format to Date time irrespective of System date time format [duplicate]

I need convert the date of string format 'MM/dd/yyyy' to datetime format 'MM/dd/yyyy' when the system date format is 'dd/MM/yyyy'.
DateTime stores a date as a numerical value, not as a string. So asking for a DateTime type of format 'MM/dd/yyyy' doesn't make much sense. If you are displaying the date in a WPF control, it will default to displaying a string that conforms to the system date format. But that is just a display string that you can manipulate using the format strings alluded to in the links above. Using #Sajeetharan's code will create a DateTime struct with the correct value internally. How you display it is up to you and your string formatting choices.
The same goes for dates stored in a database column of type 'datetime'. The value is stored numerically. Your query editor will display the value likely in the same format as your system settings. If the date is stored as a string, then again, #Sajeetharan's code is the correct way to convert the database string into a DateTime struct.
use DateTime.ParseExact
DateTime.ParseExact("05/02/2014", "dd/MM/yyyy", CultureInfo.InvariantCulture)
.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);
This may help:
string dateString="05/02/2014";
DateTime txtmyDate = DateTime.ParseExact(dateString, "MM/dd/yyyy",
CultureInfo.InvariantCulture);
try this
string dateString="05/02/2014";
DateTime txtmyDate =convert.toDateTime(dateString);
DateTime dt = DateTime.ParseExact("05/02/2014","MM/dd/yyyy",CultureInfo.InvariantCulture);

Datetime conversion independent of system date format [duplicate]

I need convert the date of string format 'MM/dd/yyyy' to datetime format 'MM/dd/yyyy' when the system date format is 'dd/MM/yyyy'.
DateTime stores a date as a numerical value, not as a string. So asking for a DateTime type of format 'MM/dd/yyyy' doesn't make much sense. If you are displaying the date in a WPF control, it will default to displaying a string that conforms to the system date format. But that is just a display string that you can manipulate using the format strings alluded to in the links above. Using #Sajeetharan's code will create a DateTime struct with the correct value internally. How you display it is up to you and your string formatting choices.
The same goes for dates stored in a database column of type 'datetime'. The value is stored numerically. Your query editor will display the value likely in the same format as your system settings. If the date is stored as a string, then again, #Sajeetharan's code is the correct way to convert the database string into a DateTime struct.
use DateTime.ParseExact
DateTime.ParseExact("05/02/2014", "dd/MM/yyyy", CultureInfo.InvariantCulture)
.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);
This may help:
string dateString="05/02/2014";
DateTime txtmyDate = DateTime.ParseExact(dateString, "MM/dd/yyyy",
CultureInfo.InvariantCulture);
try this
string dateString="05/02/2014";
DateTime txtmyDate =convert.toDateTime(dateString);
DateTime dt = DateTime.ParseExact("05/02/2014","MM/dd/yyyy",CultureInfo.InvariantCulture);

Convert date format of string to datetime MM/dd/yyyy when system date formate is dd/MM/yyyy

I need convert the date of string format 'MM/dd/yyyy' to datetime format 'MM/dd/yyyy' when the system date format is 'dd/MM/yyyy'.
DateTime stores a date as a numerical value, not as a string. So asking for a DateTime type of format 'MM/dd/yyyy' doesn't make much sense. If you are displaying the date in a WPF control, it will default to displaying a string that conforms to the system date format. But that is just a display string that you can manipulate using the format strings alluded to in the links above. Using #Sajeetharan's code will create a DateTime struct with the correct value internally. How you display it is up to you and your string formatting choices.
The same goes for dates stored in a database column of type 'datetime'. The value is stored numerically. Your query editor will display the value likely in the same format as your system settings. If the date is stored as a string, then again, #Sajeetharan's code is the correct way to convert the database string into a DateTime struct.
use DateTime.ParseExact
DateTime.ParseExact("05/02/2014", "dd/MM/yyyy", CultureInfo.InvariantCulture)
.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);
This may help:
string dateString="05/02/2014";
DateTime txtmyDate = DateTime.ParseExact(dateString, "MM/dd/yyyy",
CultureInfo.InvariantCulture);
try this
string dateString="05/02/2014";
DateTime txtmyDate =convert.toDateTime(dateString);
DateTime dt = DateTime.ParseExact("05/02/2014","MM/dd/yyyy",CultureInfo.InvariantCulture);

convert date string to datetime

I have date string in format dd-MMM-yyyy and want to convert this to datetime, when I use below code
DateTime.ParseExact("20-Oct-2012", "yyyy-MM-dd HH:mm tt", null)
it causing an error
String was not recognized as a valid DateTime.
When I modify above code
DateTime.ParseExact("20-Oct-2012", "dd-MMM-yyyy", null)
then I got date time in format (mm/dd/yyyy) : 10/20/2012 12:00:00 AM
But I need it should be converted in yyyy/mm/dd format. Please help me in this regard.
You should try this
DateTime.ParseExact("20-Oct-2012", "dd-MMM-yyyy", null).ToString("yyyy/mm/dd")
For further reading on formats Check This
You need to distinguish between two separate concerns: that of parsing your original string into an abstract DateTime representation, and that of converting the latter back into another string representation.
In your code, you're only tackling the former, and relying on the implicit ToString() method call (which uses the system's current locale) to convert it back to string. If you want to control the output format, you need to specify it explicitly:
// Convert from string in "dd-MMM-yyyy" format to DateTime.
DateTime dt = DateTime.ParseExact("20-Oct-2012", "dd-MMM-yyyy", null);
// Convert from DateTime to string in "yyyy/MM/dd" format.
string str = dt.ToString("yyyy/MM/dd");
Also note that the mm format specifier represents minutes; months are represented by MM.
Edit: 'Converted date contain value "10/20/2012 12:00:00 AM".' Be careful what you mean by that. The constructed DateTime value contains an abstract representation of the parsed date and time that is independent of any format.
However, in order to display it, you need to convert it back into some string representation. When you view the variable in the debugger (as you're presumably doing), Visual Studio automatically calls the parameterless ToString() method on the DateTime, which renders the date and time under the current culture (which, in your case, assumes the US culture).
To alter this behaviour such that it renders the date and time under a custom format, you need to explicitly call the ToString(string) overload (or one of the other overloads), as I've shown in the example above.
You could try this instead :
Convert.ToDateTime("20-Oct-2012").ToString("yyyy/MM/dd")
Hope this will help !!

Categories