c# convert string to date type - c#

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

Related

Parsing date form dd-MM-yyyy to dd MMM yyyy

I want to parse dd-MM-yyyy date format into dd MMM yyyy I get the reference but it cannot convert date in a proper manner it mismatches the date and month.
Suppose my date is
string dat = "11-01-2019"
and I am using
string date = DateTime.Parse(dat).ToString("dd MMM yyyy");
but it returns 01 Nov 2019. But actually, it is 11 Jan 2019 because the format of date is dd-MM-yyyy I don't understand how to correct it any method of parsing I am using it returns 01 Nov 2019 that is wrong. Please help me to resolve the issue
You'll need to specify the culture the date is formatted for. I'm assuming UK here:
var ukCulture = System.Globalization.CultureInfo.GetCultureInfo("en-gb");
string dat = "11-01-2019";
string date = DateTime.Parse(dat, ukCulture).ToString("dd MMM yyyy");
Console.WriteLine(date);
Try it online
Note that you'll get a FormatException if you enter an invalid date here, so it might be better to use TryParse:
var ukCulture = System.Globalization.CultureInfo.GetCultureInfo("en-gb");
string dat = "11-01-2019";
DateTime parsedDate;
if (DateTime.TryParse(dat, ukCulture, System.Globalization.DateTimeStyles.None, out parsedDate))
{
string date = parsedDate.ToString("dd MMM yyyy");
Console.WriteLine(date);
}
else
{
Console.WriteLine("invalid date");
}
Try it online
Adding to John's great answer, here's a list of CultureInfo codes for reference:
http://www.csharp-examples.net/culture-names/

Converting "August 2012" to DateTime object with TryParseExact

I am trying to parse a string that is of the format "August 2012" into a DateTime object. The string is coming from the column name in a DataTable.
string columnName= row[col].ToString(); // "August 2012"
Initially I tried using DateTime.TryParse() ...
bool result = DateTime.TryParse(row[col].ToString, out convertedDateTime);
but it kept returning false. So next I tried using DateTime.TryParseExact using the the proper cultureformat as described here ...
CultureInfo enUS = new CultureInfo("af-ZA");
DateTime.TryParseExact(row[col].ToString(), "y", enUS, DateTimeStyles.None, out columnNameAsDate)
However, this keep returning false also. What am I doing wrong? SHouldn't I be able to parse a string in the format August 2012 into a DateTime object?
This should give you the date expected.
string columnName= row[col].ToString(); // ==> August 2012
CultureInfo enUS = new CultureInfo("en-US");
DateTime.TryParseExact(columnName, "MMMM yyyy", enUS, DateTimeStyles.None, out columnNameAsDate);
First: You should specify the exact culture. In af-ZA culture the eighth month of the year is named "Augustus" not "August" and this will, of course, fail.
Second: You should pass the correct format specification to get the full month name (MMMM) and the year (yyyy).
I would split the string first:
DateTime outDate = new DateTime();
string[] words = columnName.Split(' ');
if(words.Length>1){
string month = words[0].Substring(0,3);
string year = words[1];
outDate = DateTime.ParseExact(month+' '+year,
"MMM yyyy", System.Globalization.CultureInfo.InvariantCulture);
}

Convert to DateTime

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

I am getting Error as String was not recognized as a valid DateTime

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

convert string to datetime in c#

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

Categories

Resources