String not getting converted to datetime - c#

I have I have Excel file from where I am getting date in string format as "30-12-1899 07:50:00:AM"
When I am trying to convert it to DATETIME then it is giving error as
String was not recognized as a valid DateTime
I am trying to convert it like this
Convert.ToDateTime(homeToSchool[7],new DateTimeFormatInfo { ShortDatePattern = "dd-MM-yyyy", DateSeparator = "-" })

Use DateTime.ParseExact
string myDate = "30-12-1899 07:50:00:AM";
DateTime dt1 = DateTime.ParseExact(myDate, "dd-MM-yyyy hh:mm:ss:tt",
CultureInfo.InvariantCulture)
For more information about Date and Time Format Strings,
Custom Date and Time Format Strings

Since you are reading this from excel I hope this would help
DateTime.FromOADate(homeToSchool[7].ToString("dd-MMM-yyyy");

Related

Date Parse triggers error in ASP.NET

I'm trying to parse a date string in mm/dd/yyyy to date type, but it triggers an error saying:
String was not recognized as a valid DateTime.
This is the code I'm using:
Dim mydate As Date
If filter = 4 Then
mydate = Date.ParseExact(datepart, "mm/dd/yy", System.Globalization.DateTimeFormatInfo.InvariantInfo)
End If
I don't understand what I did wrong, any help is appreciated.
You have two little errors in your format string:
DateTime mydate = DateTime.ParseExact("07/27/2016",
"MM/dd/yyyy",
System.Globalization.DateTimeFormatInfo.InvariantInfo);
Months are parsed by "MM" not "mm" (lower case is for minutes)
The four digit year is parsed by "yyyy" not "yy"
Your date format is wrong, use MM/dd/yyyy instead mm/dd/yy try below
Date.ParseExact(datepart, "MM/dd/yyyy", CultureInfo.InvariantCulture)
CultureInfo provider = CultureInfo.InvariantCulture;
// Parse date-only value with invariant culture.
string dateString = "06/15/2008";
string format = "d";
var result = DateTime.ParseExact(dateString, format, provider);

convert to stamp time format from string c#

I use javascript to pick a date and display the format as (11-05-2015 17:37)
and I try to parse it to date time as the code below
DateTime taskDate = Convert.ToDateTime(txtDate.Text);
and save it into my date base like
TO_DATE('" + createOn + "')
its give me and error call "String was not recognized as a valid DateTime."
anyone have any others method to parse it to stamptime ?
the txtDate.Text value is 27-05-2015 09:37.
Convert.ToDateTime uses your current thread culture format when converting from string to datetime.
If string you converting from has another format, you need to use DateTime.ParseExact and explicitly provide appropriate format.
For example, in you case it should be
DateTime taskDate = DateTime.ParseExact("11-05-2015 17:37", "dd-MM-yyyy HH:mm", CultureInfo.InvariantCulture);
Also have a look to custom datetime format strings for your reference.
You can use DateTime.ParseExact or DateTime.TryParseExact
Check below code:
DateTime taskDate = DateTime.ParseExact(txtDate.Text, "dd-MM-yyyy hh:mm", CultureInfo.InvariantCulture);
Or
DateTime taskDate;
if (DateTime.TryParseExact(txtDate.Text, "dd-MM-yyyy hh:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out taskDate))
{
//code if date valid
}
else
{
//code if date invalid
}

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.

How to convert any date format to yyyy-MM-dd

My app parses a string data, extracts the date and identify the format of the date and convert it to yyyy-MM-dd.
The source date could be anything lime dd-mm-yyyy, dd/mm/yyyy, mm-dd-yyyy, mm/dd/yyyy or even yyyy-MM-dd.
Other than attempting different permutations and combinations using switch case, is there any other efficient way to do it?
string sourceDate = "31-08-2012";
String.Format("{0:yyyy-MM-dd}", sourceDate);
The above code simply returns the same sourceDate "31-08-2012".
string DateString = "11/12/2009";
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime dateVal = DateTime.ParseExact(DateString, "yyyy-MM-dd", culture);
These Links might also Help you
DateTime.ToString() Patterns
String Format for DateTime [C#]
Convert your string to DateTime and then use DateTime.ToString("yyyy-MM-dd");
DateTime temp = DateTime.ParseExact(sourceDate, "dd-MM-yyyy", CultureInfo.InvariantCulture);
string str = temp.ToString("yyyy-MM-dd");
string sourceDateText = "31-08-2012";
DateTime sourceDate = DateTime.Parse(sourceDateText, "dd-MM-yyyy")
string formatted = sourceDate.ToString("yyyy-MM-dd");
You can write your possible date formats in array and parse date as following:
public static void Main(string[] args)
{
string dd = "12/31/2015"; //or 31/12/2015
DateTime startDate;
string[] formats = { "dd/MM/yyyy", "dd/M/yyyy", "d/M/yyyy", "d/MM/yyyy",
"dd/MM/yy", "dd/M/yy", "d/M/yy", "d/MM/yy", "MM/dd/yyyy"};
DateTime.TryParseExact(dd, formats,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out startDate);
Console.WriteLine(startDate.ToString("yyyy-MM-dd"));
}
You can change your Date Format From dd/MM/yyyy to yyyy-MM-dd in following way:
string date = DateTime.ParseExact(SourceDate, "dd/MM/yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");
Here, SourceDate is variable in which you will get selected date.
You will need to parse the input to a DateTime object and then convert it to any text format you want.
If you are not sure what format you will get, you can restrict the user to a fixed format by using validation or datetimePicker, or some other component.
This is your primary problem:
The source date could be anything like dd-mm-yyyy, dd/mm/yyyy,
mm-dd-yyyy, mm/dd/yyyy or even yyyy-MM-dd.
If you're given 01/02/2013, is it Jan 2 or Feb 1? You should solve this problem first and parsing the input will be much easier.
I suggest you take a step back and explore what you are trying to solve in more detail.
Try this code:
lblUDate.Text = DateTime.Parse(ds.Tables[0].Rows[0]["AppMstRealPaidTime"].ToString()).ToString("yyyy-MM-dd");
if (DateTime.TryParse(datetoparser, out dateValue))
{
string formatedDate = dateValue.ToString("yyyy-MM-dd");
}
string sourceDate = "15/06/2021T00.00.00";
DateTime Date = DateTime.Parse(sourceDate)
string date = Date.ToString("yyyy-MM-dd");
Convert.toDateTime(sourceDate).toString("yyyy-MM-dd");
Convert.ToDateTime((string)item["LeaveFromDate"]).ToString("dd/MM/yyyy")
This might be helpful

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

Categories

Resources