convert string to datetime in c# - 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

Related

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

How to convert string date in dateTime?

I have date in string format. I want to convert in date time in following format. I have referred few links but didn't get exact output.
String date = "03-23-16"; //MM-dd-yy
Requirement: it should be in date format like "March 23, 2016"
Can anybody suggest me how to convert this?
You could convert it to DateTime by using, say, DateTime.ParseExact and then convert it back to string using format "MMMM dd, yyyy":
String date = "03-23-16"; //MM-dd-yy note that MM here
DateTime dtInstance = DateTime.ParseExact(date, "MM-dd-yy", null); //this is how you convert string to DateTime
string newDate = dtInstance.ToString("MMMM dd, yyyy"); //this is how you convert it back with format as you want
Also, note that mm is minutes format in C# DateTime while MM is months.
DateTime.ParseExact("03-23-16", "MM-dd-yy", null).ToString("MMMM dd, yyyy")
You could convert it to Long Date Format by using ToLOngDateString()
string date = "03-05-16";
date = date.Replace('-', '/');
DateTime dt = Convert.ToDateTime(date);
string newDate = dt.ToLongDateString();
it will print :March, 03, 2016.
try this:
string date = "01-08-2008";
DateTime dt = DateTime.ParseExact("24/01/2013", "mm-dd-yy", CultureInfo.InvariantCulture);
parse to string:
dt.ToString("MMMM dd, yyyy");

Format ISO datetime to March 12th, 2014 12:00:00

How can I turn an ISO date (20140312120000 or 2014-03-12 12:00:00) into "March 12th, 2014 12:00:00"?.
Thanks.
DateTime thisDate1 = new DateTime(2014, 3, 12);
Console.WriteLine("Today is " + thisDate1.ToString("MMMM dd, yyyy") + ".");
// The example displays the following output:
// Today is March 12, 2011.
You can't parse it with the normal DateTime.Parse method,
DateTime.ParseExact(date, "yyyyMMdd''HHmmss", CultureInfo.InvariantCulture)
I solved it like so: DateTime.Parse(isodate).ToString("MMMM dd, yyyy HH:mm:ss").
What you want to do is to parse the input string as a DateTime and then convert it to the form you want. The ParseExact and ToString methods will do the job.
public string MyFromat(string s)
{
var inputForms = new string[]
{
"yyyyMMdd''HHmmss",
"yyyy-MM-dd' 'HH':'mm':'ss"
};
var time = DateTime.ParseExact(s, inputForms, , CultureInfo.InvariantCulture);
return time.ToString(""MMMM dd, yyyy HH':'mm':'dd", , CultureInfo.InvariantCulture);
}
Your two example forms are not ISO. If you want to parse ISO date times, then use DateTimeOffset for representing the time and use these input forms:
static readonly string[] Iso8061DateTimeForms = new string[]
{
"yyyyMMdd'T'HHmmss",
"yyyyMMdd'T'HHmmss'Z'",
"yyyyMMdd'T'HHmmsszzz",
"yyyyMMdd'T'HHmmss'.'fffffff",
"yyyyMMdd'T'HHmmss'.'fffffff'Z'",
"yyyyMMdd'T'HHmmss'.'fffffffzzz",
"yyyy'-'MM'-'dd'T'HH':'mm':'ss",
"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'",
"yyyy'-'MM'-'dd'T'HH':'mm':'sszzz",
"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffff",
"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffff'Z'",
"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffzzz",
};
The full implementation for parsing an ISO 8061 time is:
public static DateTimeOffset ParseIso8061Time(string s)
{
var styles = DateTimeStyles.AllowWhiteSpaces |
(s.EndsWith("Z")
? DateTimeStyles.AssumeUniversal
: DateTimeStyles.AssumeLocal);
return DateTimeOffset.ParseExact(s, Iso8061DateTimeForms,
CultureInfo.InvariantCulture, styles);
}

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

c# convert string to date type

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

Categories

Resources