Parse string to DateTime with format "MMMM yyyy" - c#

I'm trying to parse a string that contains a month and a year ("April 2017" for example) into a DateTime:
var foo = DateTime.ParseExact(dateToParse, "MMMM yyyy", null, DateTimeStyles.None);
However the format of the result is 04/01/2017 00:00:00 instead of April 2017. Did I miss something?

"I'm trying to parse a string" and parsing your string to DateTime worked without a problem.
A DateTime has a value and no format, if you want to get again another sting which represents that DateTime in a specific format you have to use DateTime.ToString.
For example:
DateTime dt = DateTime.ParseExact("April 2017", "MMMM yyyy", null, DateTimeStyles.None);
string monthAndYear = dt.ToString("MMMM yyyy"); // same as your original string "April 2017"

04/01/2017 00:00:00 is the formatted output with default formatting of the value of the DateTime instance you parsed.
DateTime does not have an implicit format.
If you want to display it in the form you mentioned you need to do something like foo.ToString("MMMM yyyy")

Related

How to convert datetime format in c#?

I want to convert the DateTime format using c#. This is my code
string date = "Thu May 20 2021 00:00:00 GMT-0700 (Pacific Daylight Time)";
var s = DateTime.ParseExact(date, "dd-MM-yyyy HH:mm:ss", null);
But this code not working the exception is 'System.FormatException: 'String was not recognized as a valid DateTime.'
The format you provide must match with the format used in the string. Hence the name ParseExact. After playing around a bit I was able to match these:
string date = "Thu May 20 2021 00:00:00 GMT-0700"
var s = DateTime.ParseExact(date, "ddd MMM dd yyyy HH:mm:ss \"GMT\"zzz", null);
You may need to manually truncate the (Pacific Daylight Time) or include it in the format as a literal (like I did with GMT here).
For more information you can work with DateTime format specifiers
Your format string means that the date value must be something like that:
string date = "20-05-2021 12:00:00";
var s = DateTime.ParseExact(date, "dd-MM-yyyy HH:mm:ss", null);
Try to use an other date value or change the date format string.
You can find a lot of good examples here:
https://learn.microsoft.com/en-us/dotnet/api/system.datetime.parseexact?view=net-5.0#System_DateTime_ParseExact_System_String_System_String_System_IFormatProvider_

convert month name to month number when date is not given

From my UI Iam getting string like 'March 2017' and I want first date of this month in c#.net.how can I achieve this?In jquery calendar only months are visible.so only Iam getting 'March 2017'
I have tried this-
string pattern = "MM-dd-yy";
DateTime parsedDate;
DateTime.TryParseExact(txtDate.Text.Trim(), pattern, null, DateTimeStyles.None, out parsedDate);
You should use proper format string. MMMM represents long month name (just like "March" or "April"). yyyy represents full (4-digit) year. Returned date will be first day of the given month, just like you need:
DateTime parsedDate = DateTime.ParseExact(txtDate.Text.Trim(), "MMMM yyyy", CultureInfo.InvariantCulture);
// or CultureInfo.CurrentCulture, depending on requirements.
Or with TryParseExact:
DateTime parsedDate;
if (DateTime.TryParseExact(txtDate.Text.Trim(), "MMMM yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate)) {
// do stuff
}
If month names are always in english (like "March") - use CultureInfo.InvariantCulture. Otherwise - use appropriate culture.

Convert custom date to mysql datetime

I have a custom date format that I want to convert to Datetime so I can then insert into my database, I tried using Datetime.ParseExact() But I think I'm misunderstanding something as the code throws a System.FormatException.
I have the following date format from a csv
> 6/11/2014 9:00
and I wish to convert it to the mysql datetime format
> 0000-00-00 00:00:00 OR yyyy-MM-dd HH:mm:ss
Notice they haven't included the seconds in the original date so I am unsure (without appending them to the end) how to set all records to just have "00" for seconds as it is not available.
I tried the following which throws an exception
DateTime myDate = DateTime.ParseExact("6/11/2014 9:00", "yyyy-MM-dd HH:mm",
System.Globalization.CultureInfo.InvariantCulture);
first thing you need to convert string to date time and than convert datetime tos tring
string strd = "6/11/2014 9:00";
DateTime dt ;
//convert datetime string to datetime
if(DateTime.TryParse(strd, out dt))
{
//convert datetime to custom datetime format
Console.WriteLine("The current date and time: {0: yyyy-MM-dd HH:mm:ss}",
dt); ;
}
output
I know this is late to answer that but I'm really surprised none of answer consider to use IFormatProvider to prevent a possible parsing error because of / format specifier or considering your string is a standard date and time format for your CurrentCulture or not so you can or can't use DateTime.TryParse(string, out DateTime) overload directly.
First of all, let's look at what DateTime.ParseExact documentation says:
Converts the specified string representation of a date and time to its
DateTime equivalent. The format of the string representation must
match a specified format exactly or an exception is thrown.
In your case, they don't match. You should use d/MM/yyyy H:mm format to parse your example string with a culture that have / as a DateSeparator. I almost always suggest to use DateTime.TryParseExact method in this kind of situations;
string s = "6/11/2014 9:00";
DateTime dt;
if(DateTime.TryParseExact(s, "d/MM/yyyy H:mm", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
Console.WriteLine(dt.ToString("yyyy-MM-dd HH:mm:ss"));
// result will be 2014-11-06 09:00:00
}
If you know formats of your dates, then you can do this:
string stringDate = "6/11/2014 9:00";
//Your date formats of input
string[] dateFormats = new string[]
{
"d/MM/yyyy H:mm",
"dd/MM/yyyy H:mm",
"dd/MM/yyyy HH:mm",
"dd/MM/yyyy H:mm:ss",
"dd/MM/yyyy HH:mm:ss"
/* And other formats */
};
DateTime convertedDate;
bool isSuccessful = DateTime.TryParseExact(stringDate, dateFormats,
System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out convertedDate);
if (isSuccessful)
{
//If conversion was successful then you can print your date at any format you like
//because you have your date as DateTime object
Console.WriteLine(convertedDate.ToString("dd-MM-yyyy HH:mm:ss")); /* Or other format you want to print */
}
I hope it will be helpful to you.

How to convert 31/03/2011 00:00:00 date format to 31 Mar 2011 in C#

I have got below date format in my result,I am using C# 2.0
ExpiryDate = "31/03/2011 00:00:00";
spnExpiryDate.InnerHtml = ExpiryDate;
Now when I am going to show this in HTML it should be converted to 31 Mar 2011 format.
Please suggest!
First, parse the string to a DateTime, and then format it using the DateTime's ToString:
DateTime myDateTime = DateTime.Parse( "31/03/2011 00:00:00" );
spnExpiryDate.InnerHtml = myDateTime.ToString("dd MMM yyyy");
This should do it:
var culture = System.Globalization.CultureInfo.CreateSpecificCulture("en-GB");
spnExpiryDate.InnerHtml = DateTime.Parse(ExpiryDate, culture).ToString("d MMM yyyy");
You can leave out the culture bits if your server's default culture is already dd/mm/yyyy.
First parse date then format how you need:
DateTime dt = DateTime.Parse("31/03/2011 00:00:00");
.InnerHtml = String.Format("{0:dd MMM yyyy}", dt);
There is good link that i use almost everytime when i need format date.
Also check this aswer about extention method for datetime formatting.
at first parse your string to DateTime
var date = DateTime.Parse("31/03/2011 00:00:00", "dd/mm/yyyy HH:mm:ss");
then user method "ToString"
date.ToString("dd MMM yyyy")
You didn't say how you are outputting it, but basically you want to provide the format when you call the ToString:
aTextBox.Text = myDate.ToString("dd MMMM yyyy");
The another way is
CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(DateTime.Now.Month);
gives you Month Name

Giving System.FormatException: String was not recognized as a valid DateTime. using datetime.ParseExact in C#

I am below code in c#, where I am converting my string type format date to datetime, but giving the error.
if (!string.IsNullOrEmpty(SessionDictionary.GetValue("UserDetails", "ExpiryDate")))
{
DateTime ExpiryDate = DateTime.ParseExact(SessionDictionary.GetValue("UserDetails", "ExpiryDate"), "dd mmm yy", null);
strDate = sitedata.FormatDate(ExpiryDate, TridionDateFormat.ShortDate);
}
else
{
strDate = "-";
}
My SessionDictionary.GetValue("UserDetails", "ExpiryDate") is string type data which returns "31/01/2011 00:00:00" format date, in above code where I am using DateTime.ParseExact it is giving me System.FormatException: String was not recognized as a valid DateTime. error.
Please suggest what is wrong.
Thanks.
The sample date you describe (31/01/2011 00:00:00) looks like a format dd/MM/YYYY HH:mm:ss, so why are you using dd mmm yyyy?
Try
DateTime.ParseExact(..., "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
Note the use of HH (24-hour clock) rather than hh (12-hour clock), and the use of InvariantCulture because some cultures use separators other than slash.
For example, if the culture is de-DE, the format "dd/MM/yyyy" would expect period as a separator (31.01.2011).
Probably because of mmm(there isn't such month format), try MMM instead.(looks like Feb/Jan/etc)
You are using the wrong format to parse the date. The correct one is:
DateTime ExpiryDate = DateTime.ParseExact(SessionDictionary.GetValue("UserDetails", "ExpiryDate"), "dd/MM/yyyy hh:mm:ss", null)
Also, if your system date format is set to dd/MM/yyyy you can simply use:
DateTime ExpiryDate = DateTime.ParseExact(SessionDictionary.GetValue("UserDetails", "ExpiryDate"), "G", null)
Try
DateTime ExpiryDate = DateTime.ParseExact(SessionDictionary.GetValue("UserDetails", "ExpiryDate"), "g", null);
or see here: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

Categories