Converting String to DateTime in C# in a particular format - c#

How can I convert a string such as 07/26/13 into a C# DateTime variable in the following format? 2013-07-26 00:00:00 (Mysql datetime)

If your CurrentCulture has MM/dd/yy as a standard date and time format, you can just use DateTime.Parse method like;
DateTime date = DateTime.Parse("07/26/13");
If it is not, you can use DateTime.ParseExact or DateTime.TryParseExact methods to parse your string with custom date and time format like;
string s = "07/26/13";
DateTime date;
if(DateTime.TryParseExact(s, "MM/dd/yy", CultureInfo.InvariantCulture,
DateTimeStyles.None, out date))
{
Console.WriteLine(date);
}
DateTime doesn't have any implicit format. It has just date and time values. String representations of it have formats. You can format your DateTime with .ToString method like;
date.ToString("yyyy-MM-dd HH:mm:ss");
And by the way, if you want to insert a DateTime value to your database, you shouldn't insert it as a string. You should use parameterized queries and pass your DateTime value to directly to your parameter.

Use TryParseExact.Before posting a question try it yourself
string date_time = "07/26/13";
DateTime d;
if (DateTime.TryParseExact(date_time, "mm/dd/yy", new CultureInfo("en-US"),
DateTimeStyles.None,
out d))
{
date_time = d.ToString("yyyy-mm-dd hh:mm:ss");
}

Related

How to Format or Pad String date with zeros?

I have date values that are formatted like this: 1/1/2015.
These are produced by a Web Service which I cannot change:
How do I Format this: 1/1/2015 to 01/01/2015, with the leading zero?
Tried this:
Console.WriteLine(String.Format("{0:[##/##/####]}", "1/1/2015"));
And this:
Console.WriteLine(String.Format("{0:MM/dd/yyyy}", "1/1/2015"));
But I get the same formatted output.
I have date values that are formatted like this
In .NET, a DateTime does not have any implicit format. It just have date and time values. Textual representation (aka string representation) of a DateTime can have a format.
If you have string like that, parse it to Datetime and get it's string representation with dd/MM/yyyy format.
string s = "1/1/2015";
DateTime dt;
if(DateTime.TryParseExact(s, "d/M/yyyy", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
dt.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture).Dump(); // 01/01/2015
}
You can try like this:
return yourDateTimeValue.ToString("MM/dd/yyyy");
Edit:
Since you are storing your date as string then try like this:
string s = "1/1/2015";
DateTime dt =
DateTime.ParseExact(s, "MM/dd/yyyy", CultureInfo.InvariantCulture);
Convert the date string into DateTime then get it as MM/dd/yyyy or whatever format you want.
DateTime.Parse("1/1/2015").ToString("MM/dd/yyyy");

Converting string to date time

I have a date which comes in a string like so:
09/25/2014 09:18:24
I need it like this (yyyy-mm-dd):
2014-09-25 09:18:24
The object that this date goes into is a nullable date.
Tried this does not work:
DateTime formattedDate;
bool result = DateTime.TryParseExact(modifiedDate, "yyyy-MM-dd",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out formattedDate);
Any clues?
Thanks in advance.
From DateTime.TryParseExact
Converts the specified string representation of a date and time to its
DateTime equivalent. The format of the string representation must
match a specified format exactly.
In your case, they are not. Use yyyy-MM-dd HH:mm:ss format instead.
string s = "2014-09-25 09:18:24";
DateTime dt;
if(DateTime.TryParseExact(s, "yyyy-MM-dd HH:mm:ss",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
Console.WriteLine(dt);
}
It is a little bit unclear but if your string is 09/25/2014 09:18:24, then you can use MM/dd/yyyy HH:mm:ss format instead. Just a tip, "/" custom format specifier has a special meaning as replace me with current culture or supplied culture date separator. That means, if your CurrentCulture or supplied culture's DateSeparator is not /, your parsing operation will fail even if your format and string matches exactly.
If you have already a DateTime and you want to format it, you can use DateTime.ToString(string) method like;
dt.ToString("yyyy-mm-dd", CultureInfo.InvariantCulture); // 2014-09-25
or
dt.ToString("yyyy-mm-dd HH:mm:ss", CultureInfo.InvariantCulture); // 2014-09-25 09:18:24
Remember, a DateTime does not have any implicit format. It just contains date and time values. String representations of them have formats.
In answer to your question, to convert it as you prefer, do it like this:
string originalDate = "09/25/2014 09:18:24";
DateTime formattedDate;
if (DateTime.TryParseExact(originalDate, "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out formattedDate))
{
string output = formattedDate.ToString("yyyy-mm-dd HH:mm:ss", CultureInfo.InvariantCulture);
}
And then output will have your desired format.
DateTime dateOf = Convert.ToDateTime("09/25/2014 09:18:24");
string myFormat = "yyyy-mm-dd";
string myDate = dateOf.ToString(myFormat); // output 2014-18-25
Datetime format

Convert a string to DateTime in C#

I am trying to convert a string to a DateTime for some hours now,
The string looks like this
"20140519-140324" and I know its in UTC
I've allready tried this
DateTime ourDateTime;
bool success = DateTime.TryParseExact(Date, "yyyy-MM-dd-HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out ourDateTime);
StartTime.Text = ourDateTime.ToString("g");
and this
DateTime ourDateTime= DateTime.ParseExact(Date, "yyyy-MM-dd-HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
StartTime.Text = ourDateTime.ToString("g");
but none of these work. What I am not doing properly?
From DateTime.TryParseExact method
Converts the specified string representation of a date and time to its
DateTime equivalent. The format of the string representation must
match a specified format exactly.
In your example, they are not. Use yyyyMMdd-HHmmss custom format instead which exactly matches with your string.
Here an example on LINQPad;
string s = "20140519-140324";
DateTime dt;
if(DateTime.TryParseExact(s, "yyyyMMdd-HHmmss", CultureInfo.InvariantCulture,
DateTimeStyles.AdjustToUniversal, out dt))
{
dt.Dump();
}
Here a demonstration.
Your DateTime.ParseExact example also won't work because of the same reason.
For more information;
Custom Date and Time Format Strings
You are using the wrong format in the TryParseExact method.
the format parameter should be an indicator to the format of the input string.
therefor you need to do this:
DateTime ourDateTime;
bool success = DateTime.TryParseExact(Date, "yyyyMMdd-HHmmss", System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out ourDateTime);
if(success) {
StartTime.Text = ourDateTime.ToString("g");
}

DateTime Converting

I am trying to convert a string into a DateTime and change its format from 05/06/2012 12:00:00 to 2012-06-05 12:00:00.000 to search in the database (SQL Server 2008 R2) DATETIME column type. The original date is coming from a calendar!
I tried this:
string Datereturn = row.Cells[9].Text;
DateTime dategiven = DateTime.ParseExact(Dategiven,
"YYYY-MM-DD hh:mm:ss[.nnn]", CultureInfo.InvariantCulture);
but it pops an error of invalid datetime
To parse 05/06/2012 12:00:00:
DateTime dategiven = DateTime.ParseExact(Dategiven,
"dd/MM/yyyy hh:mm:ss", CultureInfo.InvariantCulture);
To get a different formatted string:
string newFormat = dateGive.ToString("yyyy-MM-dd hh:mm:ss");
I suggest reading Custom Date and Time Format Strings on MSDN.
Also the different between parsing and formatting (in regards to DateTime):
Parsing means taking a string representing a datetime and getting a DateTime object from it
Formatting a DateTime is taking a DateTime object and getting a string from it, formatted as needed.
Can you try this
DateTime dategiven = DateTime.ParseExact(Dategiven, "dd/MM/yyyy hh:mm:ss", CultureInfo.InvariantCulture);

DateTime error in C#

When I enter the date in the below format then my db accepts it
22/06/2011 00:00:00
But when I enter the date in this format
mm/dd/yyyy 00:00:00
then my DB throws an error saying DateTime not recognised. My calendar gives me DateTime in mm/dd/yyyy hh:mm:ss format. How can I change that in my code to dd/mm/yyyy?
DateTime Res_date = Convert.ToDateTime(txt_DT.Text);
param[5] = new MySqlParameter("#RespondBy", MySqlDbType.DateTime);
param[5].Value = Res_date;
command.Parameters.AddWithValue("#RespondBy", Res_date);
The DateTime is entered in the txt_DT.text textbox.
How can I convert the date and then convert the string to DateTime?
I think you should use the DateTime.ParseExact method. Msdn Documentation http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx
DateTime Res_date = DateTime.ParseExact(txt_DT.Text, "MM/dd/yy hh:mm:ss", ... );
Then you can use String.Format to convert your DateTime to any format you want.
http://www.csharp-examples.net/string-format-datetime/

Categories

Resources