Parsing non-standard string date to DateTime (ParseExact won't work) - c#

I'm working on a C#-WPF parser that read lines from a document and creates objects with several fields, including a "Date added" field. Problem: the date is in a non-standard Spanish format, and I am not able to make DateTime.ParseExact work, as my research suggested. This is the code:
string input = dateAddedStringSPA; //domingo 2 septiembre 2012, 23:54:20
string format = "dddd dd MMMM yyy, HH:mm:ss";
CultureInfo cultureInfo = new CultureInfo("es-ES");
DateTime dateAddedSPA;
try
{
dateAddedSPA = DateTime.ParseExact(input, format, cultureInfo);
if (dateAddedSPA == DateTime.MinValue)
{
clipping.DateAdded = DateTime.Now; /*Added this conditional workaround to avoid an exception if parsing fails (and always fails). While this doesn't work every object will have the same date: current. */
}
else
{
clipping.DateAdded = dateAddedSPA;
}
}
catch (Exception)
{
throw new Exception("Error encountered while adding date.");
}
The comment that you can see by the side of input is the actual string format, which looks like that. "format" is my attempt to get DateTime to understand it, I also tried removing the comma after the year, still didn't work. I'm not sure if it's the culture the one causing the problems, but I'm afraid my expertise isn't enough yet to know. Thing is, parsing fails and I get the date set to 1/1/0001 12:00:00 AM. Any hint that what could be happening here?
Thanks in advance.

To make the solution more "universal" you can specify multiple formats and use TryParseExact() .NET/C# method as shown in the following demo sample code snippet:
CultureInfo cultureInfo = new CultureInfo("es-ES");
string[] formats ={"dddd d MMMM yyy, HH:mm:ss", "dddd d MMMM yyy, HH:mm:ss"};
string input = "domingo 2 septiembre 2012, 23:54:20";
DateTime dt;
if (DateTime.TryParseExact(input, formats, cultureInfo, DateTimeStyles.None, out dt));
{
if (dt<DateTime.Now)
Console.WriteLine("OK");
Console.ReadKey();
}
Hope this may help.

Related

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

DateTime.TryParseExact CultureInfo.InvariantCulture

Can anyone see what I'm doing wrong, I'm trying to parse the date to ensure its a valid date, if so convert it to the format I require.
I have tried different ways of doing this, but all return 01/01/0001 00:00:00.
value of string parseArrivalDate = 02/02/2013
DateTime ukDateFormat;
string ukFormat = "0:ddd, MMM d, yyyy";
DateTime.TryParseExact(parseArrivalDate, ukFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out ukDateFormat);
DateTime test = ukDateFormat;
-------------------------------------EDIT-------------------------------
OK sorry, I did not explain it very well. If I enter UK format say 27/02/2013, and when I had UK format as dd/MM/yyyy it worked ok, problem was when I was entering US or any other format, it was returning the incorrect date, so I was changing the format round thinking that was the problem.
It has now dawned on me after reading your comments, that I had the uk format correct 1st time, so my problem is, how can I change the code, so that any date format can be parsed correctly.
Hope that makes more sense
Thanks
Your string
"0:ddd, MMM d, yyyy"
has a number 0, a colon :, and a format corresponding to
"Wed, Mar 27, 2013"
for example, if the culture is "en-GB" ("English (United Kingdom)"). It probably comes from a String.Format, Console.WriteLine or similar method call, where it is put into braces {} to format a text, as in
Console.WriteLine("The date {0:ddd, MMM d, yyyy} was selected.", someDateTime);
It would work with code like:
string arrivalDateString = "Wed, Mar 27, 2013";
...
DateTime result;
string yourFormat = "ddd, MMM d, yyyy"; // no "0:" part
bool isOK = DateTime.TryParseExact(arrivalDateString, yourFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out result);
if (isOK)
{
// Worked! Answer is in 'result' variable
}
else
{
// Didn't work! 'result' variable holds midnight 1 January 0001
}
The format that corresponds to "27/03/2013" is "dd/MM/yyyy" (or "d/M/yyyy"). The format that corresponds to "03/27/2013" is "MM/dd/yyyy" (or "M/d/yyyy").
It is not possible to have one method that handles both styles of dates, since a string like
"01/04/2013" /* ambiguous */
could mean either
1 April 2013
January 4, 2013
so it's ambiguous, and there's no way we can tell what date is meant. See also Wikipedia: Calendar date → Date format.
your date string is: 02/02/2013 and the format you are using is "0:ddd, MMM d, yyyy" which is wrong, it should be MM/dd/yyyy if its month first.
DateTime ukDateFormat;
string ukFormat = "MM/dd/yyyy";
DateTime.TryParseExact(parseArrivalDate, ukFormat,CultureInfo.InvariantCulture,DateTimeStyles.None, out ukDateFormat);
DateTime test = ukDateFormat;
If the date you have specified contains day first then month, then use the format "dd/MM/yyyy", By the way you can using single d and M for both single digit and double digits day/month.
Currently you are getting the DateTime.MinValue, since parsing is failing because of the invalid format.
I have no idea what you expect, but your input string does not met your ukFormat pattern! So it's totally right behavior.
Change your pattern to ""dd/MM/yyyy"" to make TryParseExact work.
Your provided format looks a little strange. Try to replace it with this
string ukFormat = "dd/MM/yyyy";
And read the documentation on this.
Thanks everyone for helping me understand where I was going wrong, the code below is what I have came up with although not perfect as 03/06/2013 UK is different than the meaning of 03/06/2013 US.
I have added text above the text box asking people to use format dd/mm/yyyy.
string getArrivalDate = ArrivalDate;
string getDepartureDate = DepartureDate;
string dteFormat = "dd/MM/yyyy";
DateTime result;
string arrivalDateParse;
string departureDateParse;
bool arrival = DateTime.TryParseExact(getArrivalDate, dteFormat, new CultureInfo("en-GB"), DateTimeStyles.None, out result);
if (arrival)
{
arrivalDateParse = getArrivalDate;
}
else
{
arrivalDateParse = "notvalid";
}
bool depart = DateTime.TryParseExact(getDepartureDate, dteFormat, new CultureInfo("en-GB"), DateTimeStyles.None, out result);
if (depart)
{
departureDateParse = getDepartureDate;
}
else
{
departureDateParse = "notvalid";
}
if (arrivalDateParse == "notvalid" || departureDateParse == "notvalid")
{
if (Request.IsAjaxRequest())
{
return Json(new { Confirm = "Date not in correct format" }, JsonRequestBehavior.AllowGet);
}
else
{
TempData["Error"] = "Sorry your arrival date or departure date is not a valid format, please enter date as dd/mm/yyyy example 02/12/2013";
return View("~/Views/Shared/Error.cshtml");
}
If anyone can improve on the code, it would be appreciated.
Thanks
George
Rather than using InvariantCulture for this consider using RoundTrip style (ISO-8601). See this MSDN article: http://msdn.microsoft.com/en-us/library/bb882584.aspx

String was not recognized as a valid DateTime when parse exact

I get the following exception when converting to DateTime:
String was not recognized as a valid DateTime.
lbl_RequestDate.Text = "13/2/2013";
CultureInfo provider = CultureInfo.CurrentCulture;
string[] format = provider.DateTimeFormat.GetAllDateTimePatterns();
Follow.RequestDate = DateTime.ParseExact(lbl_RequestDate.Text, format, provider, DateTimeStyles.None);
You can use thje format d/M/yyyy, Notice the single M used for the month.
Follow.RequestDate = DateTime.ParseExact(lbl_RequestDate.Text, "d/M/yyyy", provider, DateTimeStyles.None);
The method: provider.DateTimeFormat.GetAllDateTimePatterns() returns almost 155 formats, but none of them (from your current culture seems to) supports format d/M/yyyy that is why you are getting the exception. If your date has Month as 13/02/2013 then the formats returned by the method would work since the closest format is dd/MM/yyyy in the formats array.
Maybe this will help :
DateTime.ParseExact("13/2/2013","d/M/yyyy",CultureInfo.GetCultureInfo("en-US"), DateTimeStyles.None );
notice :
d is for Day (01 is also acceptable)
M is for Month (11 is also acceptable)
Try it like this:
Follow.RequestDate = DateTime.ParseExact(lbl_RequestDate.Text, "d/M/yyyy", CultureInfo.InvariantCulture);
DateTimeFormatInfo.GetAllDateTimePatterns() method returns on my machine (tr-TR Culture) 29 format but none of these support d/M/yyyy date format, that's why you are getting FormatException.
But in my culture DateSeparator is . so I can't exactly solve this problem using CultureInfo.CurrentCulture but when I use Egypt cultureinfo (it's wrote on your profile) CultureInfo.GetCultureInfo("ar-EG") this code works without any error;
CultureInfo provider = CultureInfo.GetCultureInfo("ar-EG");
string[] format = provider.DateTimeFormat.GetAllDateTimePatterns();
DateTime d = DateTime.ParseExact("13/02/2013", format, provider, DateTimeStyles.None);
Unfortunatly your your all datetime pattern doesn't support d/M/yyyy format.
Unfortunatly, changing this string to 13/02/2013 doesn't solve this problem because as I said on before, my all formats (in tr-TR Culture) doesn't support dd/MM/yyyy format either.
My humble advice is here, list all your datetime patterns and check manually if your string is recognized format with this datetime pattern like;
string[] format = provider.DateTimeFormat.GetAllDateTimePatterns();
foreach (var f in format)
{
///
}

How to convert dates without getting 'String was not recognized as a valid DateTime.'-error?

I'm trying to convert dates for example 30/12/2000 to 2000-12-30
using this code:
System.Globalization.CultureInfo enUS = new System.Globalization.CultureInfo("en-US");
DateTime.ParseExact(row.Cells[6].ToString(), "yyyy-MM-dd", enUS);
But I'm getting this error:
String was not recognized as a valid DateTime.
Can someone help me please, Thank you in advance.
You could use DateTime.TryParse() function and check if result is true or false.
So you could try to parse date with a specified format and, if its not right, try another one and so on...
The reason why you are getting this is exactly as the exception says, the string is in an incorrect format, the reason is most likely that the machine doing the comparison has a different date time setting to yyyy-MM-dd.
If you are retrieving this from a database and the return value is of date time (or if you know that row.Cells[6] is a DateTime Field, the following should work:
System.Globalization.CultureInfo enUS = new System.Globalization.CultureInfo("en-US");
if (row.Cells[6] != null)
DateTime.ParseExact(((DateTime)row.Cells[6]).ToString("yyyy-MM-dd"), "yyyy-MM-dd", enUS);
The question is however why would you want to change the format, to display it on a form if so then you can just display it as follows:
if (row.Cells[6] != null)
TextBox1.Text = ((DateTime)row.Cells[6]).ToString("yyyy-MM-dd");
EDIT
Given that row.Cells[6] is a string, you will always have to know what the format of the string is, and if you do then it would be as simple as:
With time:
DateTime ParsedDate = DateTime.ParseExact(row.Cells[6].ToString(), "dd-MM-yyyy h:mm", enUS);
Removing time and then parsing:
DateTime ParsedDate = DateTime.ParseExact(row.Cells[6].ToString().Substring(0,10), "dd/MM/yyyy", enUS);
and then to output it in the format you want would be as simple as:
TextBox1.Text = ParsedDate.ToString("yyyy-MM-dd");
You are specifying a en-US CultureInfo object, but 30/12/2000 is not a correct US date format
Try this may resolve your issue
String oldScheduledDate = "16-05-2011";
DateFormat oldFormatter = new SimpleDateFormat("dd/MM/yyyy");
DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
try
{
Date oldDate = (Date)oldFormatter .parse(oldScheduledDate);
}
Catch(Exception ex ) { /// process exception}
System.Globalization.CultureInfo enUS = new System.Globalization.CultureInfo("en-US");
try {
DateTime.ParseExact(row.Cells[6].ToString(), "yyyy-MM-dd", enUS);
}
catch (FormatException) {
...your code instead of error...
}
I believe that the problem is your second parameter. If you are passing 30/12/200 as your input, it will fail because the second parameter is expecting it separated with dashes.
use
System.Globalization.CultureInfo.InvariantCulture
DateTime.ParseExact(((DateTime)row.Cells[6]).ToString("yyyy-MM-dd"), "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture)
;
you forgot the hours / minutes:
from the DB it comes like that (converted to string) "12/05/2011 0:00"
DateTime.ParseExact(theCellValue, "MM/dd/yyyy HH:mm", enUS).ToString("yyyy-MM-dd")
creates the string you want, but its totally stupid. you should just make sure that the datetime gets in the first place formatted as you want. (then you never have to parse it)
If your source string is in dd/MM/yyyy, then you shouldn't be using US culture (MM/dd/yyyy) to parse the string.
System.Globalization.CultureInfo enGB = new System.Globalization.CultureInfo("en-GB");
DateTime temp = DateTime.ParseExact(row.Cells[6].Text, "dd/MM/yyyy", enGB);
row.Cells[6] = temp.ToString("yyyy-MM-dd");
Put this in the RowDataBound event of your grid.
I fixed it by using
Convert.ToDateTime(row.Cells[6].Text)
See how simple it is.

Parse string to DateTime in C#

I have date and time in a string formatted like that one:
"2011-03-21 13:26" //year-month-day hour:minute
How can I parse it to System.DateTime?
I want to use functions like DateTime.Parse() or DateTime.ParseExact() if possible, to be able to specify the format of the date manually.
DateTime.Parse() will try figure out the format of the given date, and it usually does a good job. If you can guarantee dates will always be in a given format then you can use ParseExact():
string s = "2011-03-21 13:26";
DateTime dt =
DateTime.ParseExact(s, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
(But note that it is usually safer to use one of the TryParse methods in case a date is not in the expected format)
Make sure to check Custom Date and Time Format Strings when constructing format string, especially pay attention to number of letters and case (i.e. "MM" and "mm" mean very different things).
Another useful resource for C# format strings is String Formatting in C#
As I am explaining later, I would always favor the TryParse and TryParseExact methods. Because they are a bit bulky to use, I have written an extension method which makes parsing much easier:
var dtStr = "2011-03-21 13:26";
DateTime? dt = dtStr.ToDate("yyyy-MM-dd HH:mm");
Or more simply, if you want to use the date patterns of your current culture implicitly, you can use it like:
DateTime? dt = dtStr.ToDate();
In that case no specific pattern need to be specified.
Unlike Parse, ParseExact etc. it does not throw an exception, and allows you to check via
if (dt.HasValue) { // continue processing } else { // do error handling }
whether the conversion was successful (in this case dt has a value you can access via dt.Value) or not (in this case, it is null).
That even allows to use elegant shortcuts like the "Elvis"-operator ?., for example:
int? year = dtStr?.ToDate("yyyy-MM-dd HH:mm")?.Year;
Here you can also use year.HasValue to check if the conversion succeeded, and if it did not succeed then year will contain null, otherwise the year portion of the date. There is no exception thrown if the conversion failed.
Solution:  The   .ToDate()   extension method
Try it in .NetFiddle
public static class Extensions
{
/// Extension method parsing a date string to a DateTime? <para/>
/// <summary>
/// </summary>
/// <param name="dateTimeStr">The date string to parse</param>
/// <param name="dateFmt">dateFmt is optional and allows to pass
/// a parsing pattern array or one or more patterns passed
/// as string parameters</param>
/// <returns>Parsed DateTime or null</returns>
public static DateTime? ToDate(this string dateTimeStr, params string[] dateFmt)
{
// example: var dt = "2011-03-21 13:26".ToDate(new string[]{"yyyy-MM-dd HH:mm",
// "M/d/yyyy h:mm:ss tt"});
// or simpler:
// var dt = "2011-03-21 13:26".ToDate("yyyy-MM-dd HH:mm", "M/d/yyyy h:mm:ss tt");
const DateTimeStyles style = DateTimeStyles.AllowWhiteSpaces;
if (dateFmt == null)
{
var dateInfo = System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat;
dateFmt=dateInfo.GetAllDateTimePatterns();
}
var result = DateTime.TryParseExact(dateTimeStr, dateFmt, CultureInfo.InvariantCulture,
style, out var dt) ? dt : null as DateTime?;
return result;
}
}
Some information about the code
You might wonder, why I have used InvariantCulture calling TryParseExact: This is to force the function to treat format patterns always the same way (otherwise for example "." could be interpreted as decimal separator in English while it is a group separator or a date separator in German). Recall we have already queried the culture based format strings a few lines before so that is okay here.
Update: .ToDate() (without parameters) now defaults to all common date/time patterns of the thread's current culture.
Note that we need the result and dt together, because TryParseExact does not allow to use DateTime?, which we intend to return.
In C# Version 7 you could simplify the ToDate function a bit as follows:
// in C#7 only: "DateTime dt;" - no longer required, declare implicitly
if (DateTime.TryParseExact(dateTimeStr, dateFmt,
CultureInfo.InvariantCulture, style, out var dt)) result = dt;
or, if you like it even shorter:
// in C#7 only: Declaration of result as a "one-liner" ;-)
var result = DateTime.TryParseExact(dateTimeStr, dateFmt, CultureInfo.InvariantCulture,
style, out var dt) ? dt : null as DateTime?;
in which case you don't need the two declarations DateTime? result = null; and DateTime dt; at all - you can do it in one line of code.
(It would also be allowed to write out DateTime dt instead of out var dt if you prefer that).
The old style of C# would have required it the following way (I removed that from the code above):
// DateTime? result = null;
// DateTime dt;
// if (DateTime.TryParseExact(dateTimeStr, dateFmt,
// CultureInfo.InvariantCulture, style, out dt)) result = dt;
I have simplified the code further by using the params keyword: Now you don't need the 2nd overloaded method any more.
Example of usage
var dtStr="2011-03-21 13:26";
var dt=dtStr.ToDate("yyyy-MM-dd HH:mm");
if (dt.HasValue)
{
Console.WriteLine("Successful!");
// ... dt.Value now contains the converted DateTime ...
}
else
{
Console.WriteLine("Invalid date format!");
}
As you can see, this example just queries dt.HasValue to see if the conversion was successful or not. As an extra bonus, TryParseExact allows to specify strict DateTimeStyles so you know exactly whether a proper date/time string has been passed or not.
More Examples of usage
The overloaded function allows you to pass an array of valid formats used for parsing/converting dates as shown here as well (TryParseExact directly supports this), e.g.
string[] dateFmt = {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt",
"MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss",
"M/d/yyyy hh:mm tt", "M/d/yyyy hh tt",
"M/d/yyyy h:mm", "M/d/yyyy h:mm",
"MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm"};
var dtStr="5/1/2009 6:32 PM";
var dt=dtStr.ToDate(dateFmt);
If you have only a few template patterns, you can also write:
var dateStr = "2011-03-21 13:26";
var dt = dateStr.ToDate("yyyy-MM-dd HH:mm", "M/d/yyyy h:mm:ss tt");
Advanced examples
You can use the ?? operator to default to a fail-safe format, e.g.
var dtStr = "2017-12-30 11:37:00";
var dt = (dtStr.ToDate()) ?? dtStr.ToDate("yyyy-MM-dd HH:mm:ss");
In this case, the .ToDate() would use common local culture date formats, and if all these failed, it would try to use the ISO standard format "yyyy-MM-dd HH:mm:ss" as a fallback. This way, the extension function allows to "chain" different fallback formats easily.
You can even use the extension in LINQ, try this out (it's in the .NetFiddle above):
var strDateArray = new[] { "15-01-2019", "15.01.2021" };
var patterns=new[] { "dd-MM-yyyy", "dd.MM.yyyy" };
var dtRange = strDateArray.Select(s => s.ToDate(patterns));
dtRange.Dump();
which will convert the dates in the array on the fly by using the patterns and dump them to the console.
Some background about TryParseExact
Finally, Here are some comments about the background (i.e. the reason why I have written it this way):
I am preferring TryParseExact in this extension method, because you avoid exception handling - you can read in Eric Lippert's article about exceptions why you should use TryParse rather than Parse, I quote him about that topic:2)
This unfortunate design decision1) [annotation: to
let the Parse method throw an exception] was so vexing that of course
the frameworks team implemented TryParse shortly thereafter which does the right thing.
It does, but TryParse and TryParseExact both are still a lot less than comfortable to use: They force you to use an uninitialized variable as an out parameter which must not be nullable and while you're converting you need to evaluate the boolean return value - either you have to use an ifstatement immediately or you have to store the return value in an additional boolean variable so you're able to do the check later. And you can't just use the target variable without knowing if the conversion was successful or not.
In most cases you just want to know whether the conversion was successful or not (and of course the value if it was successful), so a nullable target variable which keeps all the information would be desirable and much more elegant - because the entire information is just stored in one place: That is consistent and easy to use, and much less error-prone.
The extension method I have written does exactly that (it also shows you what kind of code you would have to write every time if you're not going to use it).
I believe the benefit of .ToDate(strDateFormat) is that it looks simple and clean - as simple as the original DateTime.Parse was supposed to be - but with the ability to check if the conversion was successful, and without throwing exceptions.
1) What is meant here is that exception handling (i.e. a try { ... } catch(Exception ex) { ...} block) - which is necessary when you're using Parse because it will throw an exception if an invalid string is parsed - is not only unnecessary in this case but also annoying, and complicating your code. TryParse avoids all this as the code sample I've provided is showing.
2) Eric Lippert is a famous StackOverflow fellow and was working at Microsoft as principal developer on the C# compiler team for a couple of years.
var dateStr = #"2011-03-21 13:26";
var dateTime = DateTime.ParseExact(dateStr, "yyyy-MM-dd HH:mm", CultureInfo.CurrentCulture);
Check out this link for other format strings!
DateTime.Parse() should work fine for that string format. Reference:
http://msdn.microsoft.com/en-us/library/1k1skd40.aspx#Y1240
Is it throwing a FormatException for you?
Put the value of a human-readable string into a .NET DateTime with code like this:
DateTime.ParseExact("April 16, 2011 4:27 pm", "MMMM d, yyyy h:mm tt", null);
You can also use XmlConvert.ToDateString
var dateStr = "2011-03-21 13:26";
var parsedDate = XmlConvert.ToDateTime(dateStr, "yyyy-MM-dd hh:mm");
It is good to specify the date kind, the code is:
var anotherParsedDate = DateTime.ParseExact(dateStr, "yyyy-MM-dd hh:mm", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);
More details on different parsing options http://amir-shenodua.blogspot.ie/2017/06/datetime-parsing-in-net.html
The simple and straightforward answer -->
using System;
namespace DemoApp.App
{
public class TestClassDate
{
public static DateTime GetDate(string string_date)
{
DateTime dateValue;
if (DateTime.TryParse(string_date, out dateValue))
Console.WriteLine("Converted '{0}' to {1}.", string_date, dateValue);
else
Console.WriteLine("Unable to convert '{0}' to a date.", string_date);
return dateValue;
}
public static void Main()
{
string inString = "05/01/2009 06:32:00";
GetDate(inString);
}
}
}
/**
* Output:
* Converted '05/01/2009 06:32:00' to 5/1/2009 6:32:00 AM.
* */
Try the following code
Month = Date = DateTime.Now.Month.ToString();
Year = DateTime.Now.Year.ToString();
ViewBag.Today = System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat.GetMonthName(Int32.Parse(Month)) + Year;
DateTime.ParseExact(DateTime, Format, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite)
for example:
DateTime.ParseExact("2011-03-21 13:26", "yyyy-MM-dd hh:mm", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite);

Categories