Hi Im trying to parse date strings like "1012012", "1st January 2012".
read the Api It says to use d,%d where the date does not have a leading 0. Cant get it working for dates like "1012012"
trying to use "d MMM YYYY" for "1st January 2012", what do I use so 'st', 'th' works?
using System;
using System.IO;
using System.Globalization;
namespace test
{
class Script
{
static public void Main(string [] args)
{
//String dateString = "9022011"; // q1
String dateString = "9th February 2011"; //q2
System.DateTime date = DateTime.MinValue;
string[] format = { "ddMMyyyy", "d MMM yyyy" }; // what would be the correct format strings?
if (DateTime.TryParseExact(dateString,format,new CultureInfo("en-AU"),DateTimeStyles.None,out date))
{
Console.Out.WriteLine(date.ToString());
}
else
{
Console.Out.WriteLine("cant convert");
}
}
}
}
Only the ISO 8601 format ( YYYY-MM-DDTHH:mm:ss.sssZ ) is explicitly specified to be supported.
The DateTime. ParseExact(String, String, IFormatProvider) method parses the string representation of a date, which must be in the format defined by the format parameter.
ToString() − One more way to get the date from DateTime is using ToString() extension method. The advantage of using ToString() extension method is that we can specify the format of the date that we want to fetch. DateTime. Date − will also remove the time from the DateTime and provides us the Date only.
Use DateTime. TryParseExact to try to parse it: string text = "02/25/2008"; DateTime parsed; bool valid = DateTime. TryParseExact(text, "MM/dd/yyyy", CultureInfo.
var dateString = "1st February 2011";
DateTime date;
var replaced = dateString.Substring(0,4)
.Replace("nd","")
.Replace("th","")
.Replace("rd","")
.Replace("st","")
+ dateString.Substring(4);
DateTime.TryParseExact(replaced, "d MMMM yyyy",
new CultureInfo("en-us"), DateTimeStyles.AssumeLocal,
out date);
should do the trick (sorry the 'th' is nasty) - you have to take some care with the st (August) - just remove it only from the first few appearances:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With