I want to convert a string to a DateTime object. My string will be in this format- "18th Jul 2016" (the date can change). Obviously, .Net does not take this as a valid date format. Is there any easy way to convert this without using any third party library?
I wouldn't use String.Replace since it could be a problem is the current culture's month-name contains the strings you're going to replace.
Instead you could remove this part from the string:
string input = "18th Jul 2016";
string[] token = input.Split(); // split by space, result is a string[] with three tokens
token[0] = new string(token[0].TakeWhile(char.IsDigit).ToArray());
input = String.Join(" ", token);
DateTime dt;
if(DateTime.TryParseExact(input, "dd MMM yyyy", null, DateTimeStyles.None, out dt))
{
Console.WriteLine("Date is: " + dt.ToLongDateString());
}
If you pass null as IFormatProvider to TryParseExact the current culture's datetimeformat is used. If you want to force english names you can pass CultureInfo.InvariantCulture.
Workaround:
string dateStr = "18th Jul 2016";
dateStr = dateStr.Replace("th", "").Replace("st", "").Replace("rd", "").Replace("nd", "");
DateTime date;
if (DateTime.TryParseExact(dateStr, "dd MMM yyyy", CultureInfo.CurrentCulture,
DateTimeStyles.AssumeLocal, out date))
{
}
else
{
// error
}
Its a bit of a fudge but
string result = System.Text.RegularExpressions.Regex.Replace(dt, "[st|th|nd|rd]{2} ", " ", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
DateTime d = DateTime.Parse(result);
I included the space so it doesnt try editing the months.. I did start out with [0-9]{1,2} and replacing it with the number, but that seemed overkill
string dateString = "18th Jul 2016";
dateString = Regex.Replace(dateString, #"^(\d{2})(st|nd|rd|th)", "$1");
var result = DateTime.ParseExact(dateString, "dd MMM yyyy", CultureInfo.InvariantCulture);
Related
I have a date that I need to get into a DateTime object. In my code below I set the filedate to the date string that I get and then try two different formats (patern and patern2. It does not recognize the format and always falls down to the else block and I dont get the datetime object as I need it. I got the format string set up using the specifiers I found on MSDN on this page..
string filedate = "Tue Aug 12 16:01:29 CDT 2014";
string patern = "ddd MMM d hh:mm:ss CDT yyyy";
string patern2 = "ddd MMM dd hh:mm:ss CDT yyyy";
DateTime dat;
CultureInfo enUS = new CultureInfo("en-US");
string outString = "";
if (DateTime.TryParseExact(filedate, patern, enUS, System.Globalization.DateTimeStyles.None, out dat))
{
outString = (dat.ToShortDateString() + " " + dat.ToShortTimeString());
}
else if (DateTime.TryParseExact(filedate, patern2, enUS, System.Globalization.DateTimeStyles.None, out dat))
{
outString = (dat.ToShortDateString() + " " + dat.ToShortTimeString());
}
else
{
outString = filedate.Trim(); //always falling to here
}
Three problems:
Your two pattern straings are identical - why try them both?
hh means hour of 12-hour clock; 16 isn't a valid value
You should escape the CDT part as you want it as a literal
I suspect you want:
"ddd MMM d HH:mm:ss 'CDT' yyyy";
Additionally, if this is always in English, you probably want to use CultureInfo.InvariantCulture.
Finally, I suspect this is only going to be valid in the summer... in winter I'm guessing you'll have CST instead. Unfortunately this is a horrible format... you may well want to use string operations to strip out the CST/CDT (or whatever it is - will it always be central time?) before parsing. As far as I'm aware, there's no support for parsing those.
I'm trying to convert "1/7/2014 1:37 PM" (which is a string) to "01/07/2014 13:37" (DateTime format). What would be the best way to do this?
This is what I've got
string dateString = "1/27/2014 1:37 PM";
string format = "MM/dd/yyyy HH:mm";
DateTime dt;
bool temp = DateTime.TryParseExact(dateString, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
Console.WriteLine("bool = {0}, dt ={1}", temp, dt);
And my output is
bool = False, dt =1/1/0001 12:00:00 AM
Much thanks.
EDIT:
It's not just for the string I specified. Adding a few more cases - The LHS should get parsed exactly to the RHS
1/7/2014 1:37 PM -> 01/07/2014 13:37
11/27/2014 1:40 AM -> 11/27/2014 01:40
1/12/2014 2:05 PM -> 01/12/2014 14:05
Essentially, the input string does not have leading zeros and time is in 12 hour format and the output should have leading zeros where needed and should display the time in 24 hour format
I've tried giving
string format = "MM/dd/yyyy HH:mm tt";
but that also gives the same wrong output
bool = False, dt =1/1/0001 12:00:00 AM
Four things to change:
You need lowercase h for hours if you use the am/pm designator
You need a single h if the hour can be 1
You need to add tt for the am/pm designator
You need a single M for the month since it's 1
string dateString = "1/27/2014 1:37 PM";
string format = "M/dd/yyyy h:mm tt";
DateTime dt;
bool temp = DateTime.TryParseExact(dateString, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
Console.Write("temp: {0} date:{1}", temp, dt); // temp: True date:1/27/2014 1:37:00 PM
See: The "tt" Custom Format Specifier
Update: acccording to your edit:
I also need to convert it back to string in a specific format. It should have leading zeros and time is in 12 hour format and the output should have leading zeros where needed and should display the time in 24 hour format
1/7/2014 1:37 PM -> 01/07/2014 13:37
11/27/2014 1:40 AM -> 11/27/2014 01:40
1/12/2014 2:05 PM -> 01/12/2014 14:05
Then you can use this format string: MM/dd/yyyy HH:mm in DateTime.ToString with CultureInfo.InvariantCulture. Note that i've used uppercase HH for 24h hour format:
string output = dt.ToString("MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture);
You need InvariantCulture, otherwise / will be replaced with the actual date-separator of your current culture (f.e. . in germany).
See: The "/" Custom Format Specifier
Maybe you can try like this
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);
Console.WriteLine(String.Format("{0:MM/dd/yyyy}", dt));
You should be using
lowercase h rather than H as the time is in 12-, not 24-hour
one h rather than two as you don't have a leading zero on the hour
one M rather than two as you don't have a leading zero on the month
tt to match AM or PM.
Custom Date and Time Format Strings
You can use
Datetime dtDate = DateTime.PareExact(dt,"DateFormat of dt",cultureInfo.InavriantCulture);
Try This...
static void Main(string[] args)
{
string dateString = "1/27/2014 1:37 PM";
string format = "MM/dd/yyyy HH:mm";
DateTime dt2 = Convert.ToDateTime(dateString);
Console.WriteLine(dt2.ToString(format));
Console.ReadLine();
}
This may help:-
DateTime txtmyDate = DateTime.ParseExact(dateString "MM/dd/yyyy hh:mm",
CultureInfo.InvariantCulture);
From DateTime.TryParseExact method
Converts the specified string representation of a date and time to its
DateTime equivalent using the specified format, culture-specific
format information, and style. The format of the string representation
must match the specified format exactly.
In your case, it is not.
MM format is for 01 to 12, use M format which is 1 to 12.
HH format is for 00 to 23, use h format instead which is 1 to 12.
Also you are missing tt format which is for AM/PM designator.
string str = "1/27/2014 1:37 PM";
string format = "M/dd/yyyy h:mm tt";
DateTime dt;
bool result = DateTime.TryParseExact(str,
format,
CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt);
Console.WriteLine(result);
Output will be
True
Here a demonstration.
Your format is wrong. You are missing the AM/PM:
string format = "M/dd/yyyy h:mm tt";
Notice the tt part which is required in order to be able to properly parse the date. Also I would recommend you adding error checking:
string dateString = "1/27/2014 1:37 PM";
string format = "M/dd/yyyy h:mm tt";
DateTime dt;
bool temp = DateTime.TryParseExact(dateString, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
if (temp)
{
Console.WriteLine("bool = {0}, dt = {1:M/dd/yyyy h:mm}", temp, dt);
}
else
{
Console.WriteLine("Unable to parse date: {0}", dateString);
}
private string format = "dd/MM/yyyy HH:mm:ss";
DateTime fromdate = DateTime.ParseExact(GetFromScanDateTextBox.Text, format, CultureInfo.InvariantCulture);
I am getting error when executing this line string was not recognized as a Valid Date Time.
I have tried this also but it not works
DateTime fromdate = DateTime.ParseExact(GetFromScanDateTextBox.Text, format,null);
Your format string must be "d/M/yyyy", take a look at this.
Basically
MM : The month, from 01 through 12.
while
M : The month, from 1 through 12.
The same for the day part.
You are telling DateTime.ParseExact that you are expecting a string with format dd/MM/yyyy HH:mm:ss but you are giving it a string with format d/M/yyyy.
You need to change your format to just d/M/yyyy.
Also I suggest using DateTime.TryParseExact to verify the validity of your string instead of using exceptions.
var okay = DateTime.TryParseExact(
input,
new[] { "dd/MM/yyyy HH:mm:ss", "d/M/yyyy" },
new CultureInfo("en-GB"),
DateTimeStyles.None,
out dateTime);
If your input string is liable to change, TryParseExact allows you to define multiple formats as shown above, or alternatively, if it is always going to be with your current culture, just do DateTime.TryParse and do away with defining the format.
var okay = DateTime.TryParse(input, out dateTime);
If your format is always month/date/year and particularly in this case(if your date is 3rd Sept 2013) you can use:
string format = "MM/dd/yyyy";
string dateTime = "9/3/2013";
dateTime = (dateTime.Split('/')[0].Length == 1 ? "0" + dateTime.Split('/')[0] : dateTime.Split('/')[0]) + "/" + (dateTime.Split('/')[1].Length == 1 ? "0" + dateTime.Split('/')[1] : dateTime.Split('/')[1]) + "/" + dateTime.Split('/')[2];
DateTime fromdate = DateTime.ParseExact(dateTime, format, CultureInfo.InvariantCulture);
Do not provide the HH:MM:SS part in the format part
string format = "dd/MM/yyyy";
DateTime fromdate = DateTime.ParseExact(test.Text, format, CultureInfo.InvariantCulture);
I've got this string:
string date = "Sun, 17 Mar 2013 12:40:23 +0000";
And trying to convert to a date type but I keep getting a not in correct format error when I try the convert.
DateTime dt = Convert.ToDateTime(date);
And then trying to get it into these formats:
dt.ToString("dd")
dt.ToString("MMMM")
dt.ToString("yyyy")
You can use DateTime.ParseExact for the conversion.
Try the following code:
var date = "Sun, 17 Mar 2013 12:40:23 +0000";
var dt = DateTime.ParseExact(date, "ddd, dd MMM yyyy hh:mm:ss zzz", CultureInfo.InvariantCulture);
Console.WriteLine(dt.ToString("dd"));
Console.WriteLine(dt.ToString("MMMM"));
Console.WriteLine(dt.ToString("yyyy"));
Output:
17
March
2013
Try DateTime.TryParse() or DateTime.Parse()
Try using DateTime.Parse instead.
var dt = DateTime.Parse(date);
I would also recommend that you Parse the date using DateTime.TryParse to make sure that the date is always in a valid format.
DateTime result;
if (DateTime.TryParse(date, out result))
{
Console.WriteLine(result.ToString("dd"));
Console.WriteLine(result.ToString("MMMM"));
Console.WriteLine(result.ToString("yyyy"));
}
else
{
Console.WriteLine("Error parsing date.");
}
If you are still experiencing issues you may need to provide DateTime with a CultureInfo. This allows you to specify the exact Culture used by the parser, to ensure that the computer region settings doesn't cause any issues.
DateTime.Parse(date, new CultureInfo("en-US")); // Specific culture
DateTime.Parse(date, CultureInfo.InvariantCulture); // Culture-insensitive
// Culture-insensitive TryParse
if (DateTime.TryParse(date, out result, CultureInfo.InvariantCulture))
{...}
The normal DateTime uses the culture set by your Operating System.
You can use DateTime.Parse with CultureInfo.InvariantCulture which ignores your current culture, hence avoids possible localization issues.
DateTime dt = DateTime.Parse(date, CultureInfo.InvariantCulture);
CultureInfo.InvariantCulture is similar to the english culture and works with your string.
Demo
Have you checked DateTime.TryParse method? If you scroll down, you will notice that the last sample actually is "Fri, 15 May 2009 20:10:57 GMT", similar to your request.
You can use DateTime.Parse() method like;
string date = "Sun, 17 Mar 2013 12:40:23 +0000";
DateTime dt = DateTime.Parse(date, CultureInfo.InvariantCulture);
Console.WriteLine(dt.ToString("dd"));
Console.WriteLine(dt.ToString("MMMM"));
Console.WriteLine(dt.ToString("yyyy"));
Output will be;
17
March
2013
Here is a DEMO.
Well..If you need the result in numeric format,try as shown below
string date = "Sun, 17 Mar 2013 12:40:23 +0000";
DateTime dt = Convert.ToDateTime(date);
var day = dt.Day;
var month = dt.Month;
var year = dt.Year;
var time = dt.ToShortTimeString();
var hour = dt.Hour;
var minute = dt.Minute;
var second = dt.Second;
The Variables will return the exact numerical form.
NB: Hour will be depicted as 24 hour format
public string dateConvertion(string da)
{
string sDate = da;
sDate = sDate.Replace("-", "/");
sDate = sDate.Replace(".", "/");
string format = "dd/MM/yyyy";
DateTime dDate;
if (DateTime.TryParse(sDate, out dDate))
{
//if (DateTime.TryParseExact(sDate, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dDate))
//{
sDate = dDate.ToString("MM/dd/yyyy");
sDate = sDate.Replace("-", "/");
sDate = sDate.Replace(".", "/");
}
return sDate;
}
I have a string strDate that contains selected date.
strDate holds value in the given format- month(3 letters) dd,yyyy
example 1: Feb 22, 2011
example 2: Jul 19, 2011
How can i convert this string value into datetime format of c#?
Have a look at DateTime.Parse. Try using:
DateTime.Parse(yourDateString, CultureInfo.GetCultureInfo("en-US"));
DateTime myDateTime;
if (DateTime.TryParse(myDateString, out myDateTime) == True)
{
// successfully converted to date time
}
If you wrap it in a check of DateTime.TryParse then if there is a case where the string isn't of a correct DateTime format then an exception won't be thrown.
This way you can place an else statement of change to == False and respond to the failed parse. (instead of having to deal with en exception).
var str = "Jul 19, 2011";
DateTime date;
if (DateTime.TryParseExact(str, "MMM dd, yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
// the parsing was successful
}
Try this:
DateTime dt = DateTime.ParseExact(strDate, "MMM dd, yyyy", CultureInfo.InvariantCulture);
string myDateTimeString;
myDateTimeString = "19 Feb,2008";
DateTime dt;dt = Convert.ToDateTime(myDateTimeString);
Response.Write(dt.Day + "/" + dt.Month + "/" + dt.Year);
Check this http://msdn.microsoft.com/en-us/library/az4se3k1.aspx