C# DateTime.TryParseExact when reading string of date from Excel - c#

I'm trying to read a list of string from excel and parse it to a date.
I specified the format of the string in excel was d/M/yyyy but sometimes I got the string in the format dd/MM/yyyy, d/MM/yyyy, d/M/yyyy HH:mm:ss, dd/M/yyyy h:m:ss, ........ etc.
I don't care what the time is and I only want to get the string of date and parse it to a date. Do I need to define a huge array to contain all the combination of format of date and time before calling TryParseExact? or is there any smart way to do so?

You could Regex to rearrange the date string to M/d/y which can be parsed easily:
DateTime dt = DateTime.Parse(Regex.Replace(inputStr, #"(\d+)/(\d+)/(\d+)(.*)", #"$2/$1/$3"), CultureInfo.InvariantCulture);

Your best option is going to be to ensure that the data from excel is in the format you want, but you can split up the date string, and make a Date object from the resulting arrays:
var datePart = (excelString.Split(' '))[0];
var dateParts = datePart.Split('/');
DateTime finalDate = new DateTime(Int32.Parse(dateParts[2]), Int32.Parse(dateParts[1]), Int32.Parse(dateParts[0]));
While this will work, since it is hard-coded, it will break if the format of dd/mm/yyyy ever changes to say yyyy-mm-dd.

Related

Convert date time string in dd/mm/yyyy to datetime format mm/dd/yyyy

There is an input from CSV file which is in dd/mm/yyyy format.
I have to pass these date values to the stored procedure.
I want to convert this to mm/dd/yyyy format before I bulkcopy it to the database table from the datatable in the c# code.
Should I do this in the code or in the stored procedure which I am sending it to?
Please advise.I have tried all possible combinations.
You could you use DateTime.ParseExact,
var parsedDate = DateTime.ParseExact(dateString, "dd/MM/YYYY", CultureInfo.InvariantCulture);
where dateString is the string representation of the date you want to parse.
If your stored procedures expects a DateTime you could use the parseDate value. Otherwise, if it expects a string in the format you mentioned, you can pass the following value:
parsedDate.ToString("MM/dd/YYYY")
You should parse your value to DateTime in C# and pass this date value to your SQL client or ORM without converting it to a string
If your SQL column type is set to either one of the date value types it is quite impossible to format the date according to your desire, since the database engine does not store the formatted value but the date value itself.
Make sure to parse the DateTime in-code before updating its value in the SQL database.
string date = "2000-02-02";
DateTime time = DateTime.Parse(date); // Will throw an exception if the date is invalid.
There's also the TryParse method available for you. It will make sure the date value you're trying to parse is indeed in the right format.
string input = "2000-02-02";
DateTime dateTime;
if (DateTime.TryParse(input, out dateTime))
{
Console.WriteLine(dateTime);
}
After the storage you're more than welcome to select your preferred display format for your DateTime variable using one of the given formats (read link below for a full list of available formats).
https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx

remove time from date and print only date in datetime format

i have date stored in a string format as follows: "2014-03-12"
im passing this to a database which accepts the date as datetime.
im converting the string date to datetime format as follows:
DateTime StartDates = Convert.ToDateTime(StartDate);
but the time gets appended along with the date as "2014-03-12 12:00:00:00"
can anyone tel me how to send only the date leaving out the time.
i want the final date to be still in datetime format only but with time part cut off
DateTime is irrespective of the format. Formatting is only useful for presentation purpose. A DateTime object will have a Date part and Time part. When you try parsing your string "2014-03-12", it doesn't have a Time part, so in the parsed object, Time is set to 00:00:00.
If you just want to to display date then you can use DateTime.ToShortDateString method or use a custom format like:
string formattedDateString = StartDates.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
If you're happy with the date part, you may simply return the Date property of the DateTime conversion result:
DateTime StartDates = Convert.ToDateTime(StartDate).Date;
I should mention that using Convert.ToDateTime puts you at the mercy of the process current culture date format though, so you probably want to use the ParseExact or ToString method like the other answers suggests, with the appropriate format and culture instance.

Format Exception - string not recognized as a valid DateTime

I have an issue similar to this > Format exception String was not recognized as a valid DateTime
However, my spec requires a date format of ddMMyyyy, therefore I have modified my code but I am still getting the same error
DateTime now = DateTime.Now;
DateTime dt = DateTime.ParseExact(now.ToString(), #"ddMMyyyy", CultureInfo.InvariantCulture);
I am unclear why.
You code fails because you are attempting to parse a date in the format ddMMyyyy, when by default DateTime.ToString() will produce a format with both date and time in the current culture.
For myself in Australia that would be dd/MM/yyy hh:mm:ss p e.g. 11/10/2013 11:07:03 AM
You must realise is that the DateTime object actually stores a date as individual components (e.g. day, month, year) that only needs to be format when you output the value into whatever format you desire.
E.g.
DateTime now = DateTime.Now;
string formattedDate = now.ToString("ddMMyyyy", DateTimeFormatInfo.InvariantInfo);
For more information see the api doc:
http://msdn.microsoft.com/en-us/library/8tfzyc64.aspx
For ParseExact to work, the string coming in must match exactly the pattern matching. In the other question you mentioned, the text was coming from a web form where the format was specified to be exactly one format.
In your case you generated the date using DateTime.Now.ToString() which will not be in the format ddMMyyyy. If you want to make the date round trip, you need to specify the format both places:
DateTime now = DateTime.Now;
DateTime dt = DateTime.ParseExact(now.ToString("ddMMyyyy"), #"ddMMyyyy", CultureInfo.InvariantCulture);
Debug your code and look at what the result of now.ToString() is, it's is not in the format of "ddMMyyyy", which is why the parse is failing. If you want to output now as a string in the ddMMyyy format, then try now.ToSTring("ddMMyyyy") instead.
now.ToString() does not return a string formatted in that way. Try using now.ToString("ddMMyyyy").
You might be better off testing with a static string like "30041999"

C# Date Conversion From Euro Time To en-US Time Needed For Date Calculations

I have a date that is entered through the system (from a database) as dd/mm/yy I need to programmatically convert the date to en-US format to mm/dd/yyyy so that I can do some date calculations within the code. The code that I have so far is:
String myJames = "25/04/13" // Date String comes in as non-US date
String myJames2 = System.DateTime.Today.ToString(myJames); // I think the problem is here
DateTime d1 = Convert.ToDateTime(myJames2);
DateTime d2 = DateTime.Now;
TimeSpan t = d2 - d1;
double NrOfDays = t.TotalDays;
I know this is not completely correct, especially in the first few lines. Any help getting the dates into one en-US format for effective comparisons would be greatly appreciated.
Just to check I understand your question. You have a date as a string and you want to convert that string into a datetime so you can use it in a calculation? And your problem is that the string isn't in the format that the locale the code is running in would use?
In which case use DateTime.ParseExact.
DateTime d1 = DateTime.ParseExact(myJames,"dd/MM/yy");
This line of code would replace your line declaring and assigning d1. The line assigning to myJames2 can be removed as it isn't needed.
Everytime you convert from or to a string, culturesettings are involved.
So.. if you are converting a DateTime to string, and your culture is en-US, it will automatically converted to: MM/dd/YYYY.
This is also true for converting back. If you convert a string back to a DateTime, the culturesettings are used to see what format the string is in.
Teh culture settings are always: Thread.CurrentThread.CurrentCulture.
Most conversion functions allow to override the format (like "MM/dd/yyyy") and/or the culture. So you can create your own culture and use this during conversions.
You say the database uses dd/MM/yy, but normaly a DateTime in a database is not formatted, it is just a binary value. Or is it stored as a text? If it is stored as a text, than you should ALWAYS convert it to a DateTime using the correct culture or format.

SQL datetime to C# string and back to SQL datetime

I have a webservice method that gets data from sql of the format
2012-11-18 11:21:03 when i save it to C# string it becomes this format: 18.11.2012 11:21:03
How do i change it back to the SQL format 2012-11-18 11:21:03 ?
Parse it into a dateTime again
DateTime myTime = DateTime.Parse(myString);
and back into a proper to string
myTime.ToString("yyyy-MM-dd HH:mm:ss");
Or just read it into a datetime and cut out the middleman.
You can get the universally sortable string format (which looks like the one used by SQL server) by using the format string "u" like this:
var dateTimeString = String.Format("{0:u}", yourDateTime);
Simply run the below code,
var newDateTime = oldDateTime.Date.ToString("yyyy-MM-dd HH:mm:ss");
Its just converting it back to the SQL Format DATETIME
Trouble with Dates as strings is they are ambiguous and the formats can vary based on where you are in the world, or even local machine settings. You might assume a date string is yyyy-mm-dd but what if it is actually yyyy-dd-mm? Some dates will appear to work and some will be invalid.
In other words is 2013-02-10 the 10th of February or is it the 2nd of October? If it is just a string you have no way of knowing for sure what was intended.
Your best bet as suggested by #Haedrian is to store in a DateTime C# object, not a string. That way it is never ambiguous and you have access to various date specific functions. If you must store as a string you can convert back to a date as above or use
DateTime.TryParse(datestring, out dateVariable);
which won't throw an exception for an invalid format. Depends if you want exceptions!
Also I would suggest if you must use strings to use a 3 character month in strings, which again eliminates the ambiguity, e.g.
"dd-MMM-yy hh:mm tt"

Categories