This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How can I convert a string into datetime in .NET?
I have a string in the following format "15/03/2046". how can convert this string to a DateTime object?
My problem is when I do Convert.ToDateTime("15/03/2046") I get an exception.
when I do Convert.ToDateTime("03/03/2046") every thing works fine.
so I guess that I have to specify the format somehow while converting....
DateTime.Parse or its sister method DateTime.ParseExact.
Use DateTime.ParseExact to specify the format of the input string:
DateTime d = DateTime.ParseExact(
"15/03/2046",
"dd/MM/YYYY",
CultureInfo.InvariantCulture
);
More generic code, using extension method, and default value in case if it can't parse date
void Main()
{
var dt = "15/03/2046";
dt.ToDateTime("fr-FR", DateTime.Now).Dump();
}
public static class Extensions
{
public static DateTime ToDateTime(this string dateTime, string culture, DateTime defaultValue)
{
DateTime dt;
if (DateTime.TryParse(dateTime, System.Globalization.CultureInfo.CreateSpecificCulture(culture), System.Globalization.DateTimeStyles.None, out dt))
return dt;
else
return defaultValue;
}
}
Related
I am trying to convert a string, 20151107 to the date format of 2015-11-07.
Here's my code :
public static DateTime CustomDateFormat(this string resultdate)
{
DateTime dt = DateTime.ParseExact(resultdate, "yyyyMMdd", CultureInfo.InvariantCulture);
return dt;
}
However this returns something like this 11/07/2015 12:00:00 AM.
Any idea?
Your date returns like that because you are returning the entire DateTime object and since you are not providing a time it is default to 00:00:00.00.
If you want to return the Date in a particular format, you can use the Standard Format Strings or a Custom Format String.
In your case, you want 2015-11-07 which is a custom format of yyyy-MM-dd and can be used like so:
public static string CustomDateFormat(string resultdate)
{
DateTime dt = DateTime.ParseExact(resultdate, "yyyyMMdd", CultureInfo.InvariantCulture);
return dt.ToString("yyyy-MM-dd");
}
public static String CustomDateFormat(this string resultdate)
{
DateTime dt = DateTime.ParseExact(resultdate, "yyyyMMdd", CultureInfo.InvariantCulture);
return dt.ToString("yyyy-MMM-dd");
}
This question already has answers here:
Converting a string to DateTime object
(5 answers)
Closed 7 years ago.
I have a string which value is "2016-01-07 20:43:01,803".
I'd like to convert it use DateTime.Parse method. it is failed.
How to convert to datetime with this type of string?
You could use the ParseExact method.
var input = "2016-01-07 20:43:01,803";
DateTime dt = DateTime.ParseExact(input, "yyyy-MM-dd HH:mm:ss,fff", CultureInfo.InvariantCulture);
Try to use DateTime.ParseExact with the right format. (the last phrase is very very important: right format)
DateTime dt = DateTime.ParseExact("2016-01-07 20:43:01,803", "yyyy-MM-dd HH:mm:ss,fff", null);
This question already has answers here:
Parse string to DateTime in C#
(9 answers)
Closed 8 years ago.
This code is a simplified version of what I'm trying to do:
this.dateValue = "8/12/2005";
return DateTime.dateValue.DayOfWeek.ToString();
I want to use my dateValue in stead of 'NOW'
Use DateTime.TryParseExact
this.dateValue = "8/12/2005";
DateTime dt;
// assuming the expected date is the 8th of Dec 2005, otherwise use m/d/yyyy
if (DateTime.TryParseExact(this.dateValue, "d/m/yyyy", CulterInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
return dt.DayOfWeek.ToString();
}
else
{
return null;
}
The DateTime.Now property returns a DateTime, DayOfWeek is a property of DateTime so you can simply do
return DateTime.Now.DayOfWeek.ToString();
To get the text version of the current Day of the Week
If you want to reverse this you can parse a new DateTime from the string.
return DateTime.Parse("8/12/2005").DayOfWeek.ToString();
Watch our for strings which can't be parsed. You may want to look into the TryParse method.
This question already has answers here:
TryParse in if condition
(7 answers)
Closed 9 years ago.
Just a challenge I guess, but I hope to use TryParse in just one line :) My code:
DateTime tempDate;
user.DataNascita = DateTime.TryParse(txtDataDiNascita.Text, out tempDate) ? tempDate : (DateTime?)null;
user.DataNascita is DateTime?, and I want to return the data if TryParse is correct, null otherwise. But I need the out one (so, new line). Can't I have all in one line?
Just curious...
I'm usually using this extension method in LINQ queries:
public static DateTime? TryGetDate(this string dateString, string format = null)
{
DateTime dt;
bool success = format == null ? DateTime.TryParse(dateString, out dt) : DateTime.TryParseExact(dateString, format, null, DateTimeStyles.None, out dt);
return success ? dt : (DateTime?)null;
}
You use it in this way:
user.DataNascita = txtDataDiNascita.Text.TryGetDate();
Here's another overload with multiple formats and an IFormatProvider(different cultures):
public static DateTime? TryGetDate(this string dateString, IFormatProvider provider, params string[] formats)
{
DateTime dt;
var success = DateTime.TryParseExact(dateString, formats, provider, DateTimeStyles.None, out dt);
return success ? dt : (DateTime?)null;
}
You'd need a helper method, basically. For example:
public static DateTime? TryParseDateTime(string text)
{
DateTime validDate;
return DateTime.TryParse(text, out validDate) ? validDate : (DateTime?) null;
}
Then you can just use:
user.DataNascita = ParseHelpers.TryParseDateTime(txtDataDiNascita.Text);
You'd probably want overloads corresponding with the overloads of DateTime.TryParse and DateTime.TryParseExact, too. I wouldn't personally make this an extension method as per Tim's answer, but that's a matter of personal preference.
yea it's easy I didn't find this much of a challenge
DateTime temp; if (DateTime.TryParse(txtDataDiNascita.Text, out temp)) user.DataNascita = temp;
DateTime tempDate; user.DataNascita= DateTime.TryParse(txtDataDiNascita.Text, out tempDate) ? tempDate : (DateTime?)null;
You could do it in a single line as above. but creating your helper method is good approach.
This question already has answers here:
How to change date format from DD/MM/YYYY or MM/DD/YYYY to YYYY-MM-DD?
(4 answers)
Closed 7 years ago.
I have a datepicker which shows date in format dd/MM/yyyy(i know i coould change there itself but by client want it that way) and in database its in format MM/dd/yyyy so i do want to convert in that way.
e.g. in text box 23/09/2010 and in c sharp its convert to mm/dd/yyyy(txtbo1.text)
Regards
Indranil.
If you really store the date as a string in the DB, you can convert the string format in the following manner:
DateTime.ParseExact(dateTimeString, "dd/MM/yyyy", null).ToString("MM/dd/yyyy")
If you are storing dates in a database, you should be storing them in a field with an appropriate data type. The format shouldn't come into it. You should parse your dd/MM/yyyy text into a DateTime variable, and pass it in a parameters of a date/time type to your database.
Use regex:
public static String DMYToMDY(String input)
{
return Regex.Replace(input,
#"\b(?<day>\d{1,2})/(?<month>\d{1,2})/(?<year>\d{2,4})\b",
"${month}/${day}/${year}");
}
using System.Globalization;
string dt = DateTime.Parse(txtDate.Text.Trim()).ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);
also can be done with this
public string FormatPostingDate(string str)
{
if (str != null && str != string.Empty)
{
DateTime postingDate = Convert.ToDateTime(str);
return string.Format("{0:MM/dd/yyyy}", postingDate);
}
return string.Empty;
}