Getting an error while converting string to DateTime - c#

I am trying to convert a string value into DateTime. It gives me an error as, specified string is not in correct format.
Here is the code,
DateTime myDate = DateTime.ParseExact("07-09-2013 01:14:14:1414", "yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
string strDate = "07/09/2013 01:04:02:4";
Convert.ToDateTime(strDate);
DateTime dt = DateTime.Parse(strDate);
Please help in converting the same.
Thanks

Your format seems to be incorrect. Should be:
"dd-MM-yyyy HH:mm:ss:ffff"
Update. If number of digits representing fractions of a second varies, than the best bet is
"dd-MM-yyyy HH:mm:ss:FFFFFFF"
Refer to MSDN for other options for custom time and date formats.

Try in your page_load event:
Thread.CurrentThread.CurrentUICulture = New System.Globalization.CultureInfo("tr-TR")
Thread.CurrentThread.CurrentCulture = New System.Globalization.CultureInfo("tr-TR")

First, you mixed you years place
07-09-2013 is dd-MM-yyyy format
second, you need a :ffff after seconds
So the final line should be
DateTime myDate = DateTime.ParseExact("2013-07-09 01:14:14:1414", "yyyy-MM-dd HH:mm:ss:ffff", System.Globalization.CultureInfo.InvariantCulture);

Your format isn't correct:
"07-09-2013 01:14:14:1414"
"yyyy-MM-dd HH:mm:ss"
Atleast your date is the other way around, and the milliseconds is not specified.
Correct you format according to this: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
For the downvoter:
The correct format is specified by Andrei: "dd-MM-yyyy HH:mm:ss:ffff"

First of all, you should change your date format to dd-MM-yyyy because it fits with your date format.
Second of all, for miliseconds part, you can use . instead of :
DateTime myDate = DateTime.ParseExact("07-09-2013 01:14:14.1414", "dd-MM-yyyy HH:mm:ss.ffff", System.Globalization.CultureInfo.InvariantCulture);
string strDate = "07/09/2013 01:04:02.4";
Convert.ToDateTime(strDate);
DateTime dt = DateTime.Parse(strDate);
Here a DEMO.
For more information, check Custom Date and Time Format Strings

Related

c# convert yyyymmdd text to dd/MM/yyyy

I have some text in rows as yyyymmdd (eg: 20181211) which I need to convert to dd/MM/yyyy
I am using:
cashRow["BusinessDate"] = Convert.ToDateTime(row.Cells[ClosingDate.Index].Value.ToString()).ToString("dd/MM/yyyy");
I get the error "string was not recognized as a valid DateTime.
Any ideas where I am going wrong?
You'll need to use ParseExact (or TryParseExact) to parse the date:
var date = "20181217";
var parsedDate = DateTime.ParseExact(date, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);
var formattedDate = parsedDate.ToString("dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture)
Here we tell ParseExact to expect our date in yyyyMMdd format, and then we tell it to format the parsed date in dd/MM/yyyy format.
Applying it to your code:
cashRow["BusinessDate"] = DateTime.ParseExact(row.Cells[ClosingDate.Index].Value.ToString(), "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture).ToString("dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
You have to use ParseExact to convert your yyyyMMdd string to DateTime as follows and then everything is okay.
cashRow["BusinessDate"] = DateTime.ParseExact(row.Cells[ClosingDate.Index].Value.ToString(), "yyyyMMdd", CultureInfo.InvariantCulture).ToString("dd/MM/yyyy");
As you already know the exact format of your input yyyyMMdd (eg: 20181211), just supply it to DateTime.ParseExact() and then call ToString() on the returned DateTime object.
string YourOutput = DateTime.ParseExact(p_dates, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture).ToString("dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
Try this:
cashRow["BusinessDate"] = row.Cells[ClosingDate.Index].Value.ToString("dd/MM/yyyy");

System.FormatException: String was not recognized as a valid DateTime - when trying to convert MM/DD/YYYY

I have following C# method:
DateTime ConvertStringToDate(string dateInString)
{
try {
//string SSD = dateInString;
//DateTime date = Convert.ToDateTime(SSD);
//string strDate = String.Format("{0:yyyy-MM-dd HH:mm:ss.fff}", date);
//return Convert.ToDateTime(strDate);
return DateTime.ParseExact(dateInString, "MM/dd/yyyy", CultureInfo.InvariantCulture);
}
catch (Exception) { }
return DateTime.Today;
}
The code in comment is another way I tried before.
I am in India and developing an ASP.NET WebForms application for my client in US. On one of its forms my client will enter the date in TextBox like 6/20/2018 which is MM/dd/yyyy format.
But in both the ways I am getting this error: System.FormatException: 'String was not recognized as a valid DateTime.'
I tried many solutions on SO but none of them are working.
return DateTime.ParseExact(dateInString, "M/d/yyyy", CultureInfo.InvariantCulture);
Check it here
The difference between my answer and Fabulous' one is that I also shortened dd to d so if your user writes 6/6/2018 it will work too
Your date format is MM/dd/yyyy and your input doesn't match. It is M/dd/yyyy
Based on your comment, to solve the 6/1/2018 issue, you'll need to do it as follows M/d/yyyy
Your format string is missing the AM/PM deisgnator:
return DateTime.ParseExact
(dateInString + " 12:00:00 AM", "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
// Here ---------------------------------------------^
Try without concatenation with string " AM"
I was getting the same exception a couple of days ago when it was 9th of July, I simply appended a 0 with 9 to match the date format.
Try appending a 0 in your month to match the MM in your date format
Sometimes your system time and date format is not same as test format you can try to change system date and time format
If you want to convert this (01-01-2022) type of string into date
then try below code.
DateTime date = DateTime.ParseExact("01-01-2022", "MM-dd-yyyy", CultureInfo.InvariantCulture);
If you want to convert this (01/01/2022) type of string into date
then try below code.
DateTime date = DateTime.ParseExact("01-01-2022", "MM/dd/yyyy", CultureInfo.InvariantCulture);

DateTime convert in c#

I have DateTime variable in this format "dd/mm/yyyy hh:mm:ss".
I would like to convert this to "mm/dd/yyyy hh:mm:ss". (Month before day)
I tried to use DateTime.parse like this:
DateTime dt = new DateTime();
dt = dateTimePicker1.Value;
dt = DateTime.Parse(dt.ToString(), "mm/dd/yyyy", null);
but it wont work.
I also try it with DateTime.ParseExact() but still nothing happened.
Any suggestion?
A DateTime doesn't have any implicit format. It just has date and time values.
Formatting subject only applies when you try to get it's textual representation. If you wanna get string represetation of it, you can use .ToString() method like;
string s = dateTimePicker1.Value.ToString("MM/dd/yyyy hh:mm:ss",
CultureInfo.InvariantCulture);
And remember, mm specifier is for minutes, MM specifier is for months. Also hh specifier is for 12-hour clock and HH specifier is for 24-hour clock representations. You might wanna use HH instead.
I used InvariantCulture as a second parameter because / and : have special meaning as replace me current culture or supplied culture date or time separator.
string date = dateTimePicker1.Value.ToString("MM/dd/yyyy");
You can also use this below code for advance:
GregorianCalendar cal = new GregorianCalendar(); // or any type of calendar you want ...
string formatted = string.Format("{1:00}/{2:00}/{0} {3:00}:{4:00}:{5:00} ",
cal.GetYear(dt), cal.GetMonth(dt), cal.GetDayOfMonth(dt) , cal.GetHour(dt), cal.GetMinute(dt), cal.GetSecond(dt));
DateTime time = DateTime.Now;
string format = "MMM ddd d HH:mm yyyy";
Console.WriteLine(time.ToString(format));

Issue in Converting Date Time c#

I am facing an issue when converting the datetime
var date = DateTime.Now;
txtdate.Text = date.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
//I need to pass it later to as a DateTime variable. When i re-convert it gives me an error)
DateTime dtReconvert =Convert.toDateTime(txtdate.Text); //Error String was not recognized as a valid DateTim
When i set the datetime to something like "01/01/2013"
and convert it to Date Time it not giving me any error.
Use DateTime.ParseExact with the format "dd/MM/yyyy"
DateTime dtObject = DateTime.ParseExact(txtdate.Text,
"dd/MM/yyyy",
CultureInfo.InvariantCulture);
try this
DateTime.ParseExact(txtdate.Text, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture)
or
Convert.ToDateTime(txtdate.Text, CultureInfo.InvariantCulture)
Microsoft have adopted MM/dd/yyyy as a culture-agnostic format, it's an ambiguous format which isn't something that I would want to build a large system on.

Parsing datetime of the format "2013-Jan-31" throws error

I have a datetime column in database.
DateTime end_date = DateTime.ParseExact("2013-Jan-31", "yyyy-MM-dd", CultureInfo.InvariantCulture);
Why isn't this working?
This is not working because MM would mean January to be 01. If this is the format of the date you're trying to parse, try the format "yyyy-MMM-dd".
Hope this helps
Try like this;
DateTime a = DateTime.ParseExact("2013-Jan-31", "yyyy-MMM-dd", System.Globalization.CultureInfo.InvariantCulture);
Console.WriteLine (a);
Output:
31.01.2013
Look at from MSDN Custom Date and Time Format Strings
To use such a name of the month you need to take "MMM" so it will be
myObject.end_date = DateTime.ParseExact("2013-Jan-31", "yyyy-MMM-dd", System.Globalization.CultureInfo.InvariantCulture);
MM represents a two-digit numerical month (such as "01").
MMM represents the abbreviated month (such as "Jan").
Which means that you need
myObject.end_date = DateTime.ParseExact("2013-Jan-31", "yyyy-MMM-dd", System.Globalization.CultureInfo.InvariantCulture);
See http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx for a list of string format specifiers.

Categories

Resources