priya thapliyal
priya thapliyal

Reputation: 81

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);

Upvotes: 0

Views: 697

Answers (1)

Evk
Evk

Reputation: 101633

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.

Upvotes: 1

Related Questions