Reading Time HH:mm:ss from excel cell in c# - c#

I need to extract the time from an excel file. The time in excel is expressed in hours:minutes:seconds. The c# code i have that reads the time is:
DateTime dt = DateTime.Parse(worksheet.Cells[row, 3].Value.ToString());
string GetTime = String.Format("{0:t}", dt);
This code works perfect with one file but when i insert another similar file it does not reads the time. Does anyone know why this happens.
Excel table that DOES read the time:
Id
Date
Time
1
18/11/2022
11:51:00
Excel table that DOES NOT read the time:
Id
Date
Time
1
08/08/2022
06:54:00

Excel supports dates natively. Dates are stored in binary form (specifically a floating point number), not as text. They have no format. How they're displayed depends on the cell's numeric format and the end user's locale settings, but the actual value remains binary.
Even when you see a time text in a field, the underlying value is a DateTime whose numeric style shows only the time part. You can test that by changing the cell's numeric style to a full date time or number.
All Excel libraries will load Excel dates as .NET DateTime values. If the Excel sheet contains actual dates, Value is already a DateTime. To get its time part use the DateTime.TimeOfDay property.
For example :
TimeSpan time = ((DateTime)worksheet.Cells[row, 3].Value).TimeOfDay;

I found the solution you have to use FromOADate to get the correct format.
DateTime dt = DateTime.FromOADate((double)worksheet.Cells[row, 3].Value);

Related

Date format problem in C#? While retrieving data from Excel

Below is the image of my code please have a look on it.
I am trying to retrieve data from excel sheet and storing it into database table through SQL bulkcopy.
Error:
The date format is 05-01-2019; it is inserted as 2019-05-01 (database) incorrectly - correct date is 2019-01-05.
When date is greater than 12 it stores in correct format.
2019-12-25 (database) correct
Excel : 25-12-2019
convert your string to a date first with
DateTime.ParseExact("25-12-1986", "dd-MM-yyyy", NULL)
then format it into your date
you can also consider TryParseExact to check for wrong format
your problem is that 05-01-2019 tends to mean 'May 1st 2019' in US style date formats, therefore you need to be very careful with formats. The policy of automatically making 25-12-1966 into 25th December (which is all it could be interpreted as) is not as helpful as it seems.

Unable to correctly parse a date from Excel cell

I'm importing Excel rows and one of the columns is a Date field. There are two scenarios in which I receive the date.
The first is I receive the date correctly as a Double. For this scenario a simple DateTime.FromOADate(parsedDouble) works.
The second scenario is for whatever reason, the client has not properly formatted the cell or the value in the cell has not been recognised correctly although is a valid date. For example the date will be 1/12/2016 which in the UK format is 1st December 2016. Excel also passes format information for the cell, so in this case it passes through the cell format "dd/mm/yyyy". This is the correct day/month/year format in excel however I need to be able to parse it in c# and I'm unable to because lower case mm is minutes and not months.
So the following won't work.
var x = DateTime.ParseExact("12/12/2016", "dd/mm/yyyy", System.Globalization.CultureInfo.InvariantCulture);
It will output 12/01/2016 00:12:00
I've had a look around and can't seem to find anyone else having the same issue and I'm not quite sure how to deal with this.
An obvious (undesirable) solution would be to hack it and map the excel format of dd/mm/yyyy to dd/MM/yyyy.

display a timespan in excel

I have a timespan stored as a varchar in sql in the format of totalhours-totalminutes-totalseconds.
Now I have to export that information into excel.
The problem I'm having is that I can not for the life of me find a format within excel that will display this information correctly. Is there a way in which this information can be displayed correctly? I am using XLS in C# to output this info.
Sample input: 48:00:11
Sample output: 1900/02/17 12:11:00 AM or 48.0076388888889
For formatting, you need to set a custom time format:
[h]:mm:ss
...which will show numbers of hours for durations longer than 24 hours. If you type "48:00:11" into an Excel cell, it will create that custom format for you (at least, it did in Excel 2007 on my machine just now). Removing formatting shows the value to be the expected double (which all non-strings are): 2.000127, which is the number of days (with time as fraction) for the duration.
Putting that string value into a worksheet from C# may have a different outcome: I suspect so from the 48.007638... value you obtained. Since you have C# at your disposal I would be inclined to calculate the timespan as a number of days prior to pushing the value to Excel, then formatting as above.

Excel Shows "#########" when i try to write DateTime.Now.tostring() to one of the cell in Excel File

I have created a application in c# , it reads excel file and after checking some conditions, it select a row to be written in another Excel File.
Everything is working fine, but i need to end the file with the DateTime.Now.ToString().
string date = DateTime.Now.ToString();
ExcelWorkSheet2.Cells[newFileRow, 1] = date;
When I see the file created, it shows "########" symbol instead of actual date. When I select that cell , it changes to correct date format.
What may be going wrong?
##### is typically shown by Excel when the value in the cell is too wide. What happens if you try to expand the column width a little bit?
You need to expand the size of the cell to make it display properly. This is most easily done by double clicking on the column header to make it expand to fit all data.
Just try widening the column display a little.
As the others have said, the column isn't wide enough for your datetime value.
Without putting anything in the brackets, DateTime.Now.ToString() will return every detail of the current date.
You can cut this down by putting some speech marks in between the brackets, followed by some formatting information.
dd for current date
MM for current month
yyyy for current year
hh for current hour
mm for current minute (notice the lowercase)
ss for current second
So for example, if you just wanted the date without any time information, you would put the following which would return 2012-03-25:
var thisString = DateTime.Now.ToString("yyyy-MM-dd");
Thanks
I think you might want to shorten DateTime format and/or widen your cell a bit.
Please refer to this information on DateTime formatting.
More:
DateTime.Now.ToString() usually produces long string, something like "3/25/2012 7:26:26 PM". If this is something you would like to display, then the only option for you is to make your cell/column wider.
Otherwise consider one of many formats that suit you well.
Example: DateTime.Now.ToString("MM-dd-yy")

DateTime problem when day <= 12

I've looked around a lot and short of writing a horrible chunk of code to manipulate the string, I'd like to ask if anyone knows a nice way of sorting it:
I have a bunch of date strings in cells that I'm pulling out such as:
03/05/2011
27/05/2011
31/05/2011
03/05/2011
09/05/2011
31/05/2011
etc.
While I'm reading any entires where the day can be construed as a month - i.e. entries 1, 4 and 5 above - it gets put in as a DateTime with the day and month swapped.
For example, 03/05/2011 gets read in as a DateTime "05/03/2011 00:00:00"
The others are all read and nicely provide me with a simple string of "27/05/2011".
I'm getting this info from Excel, using
((Excel.Range)worksheet.Cells[rowCount, 3]).Value.ToString()
If I try Value2 as with my other lines, it reads those odd dates as things like "40607" but again, will read the other dates normally.
If you use the DateTime.ParseExact function to convert a string to a DateTime object, you can specify the specific format used by your dates (which looks like "day/month/year") without having to do any string manipulation whatsoever.
Example:
var dateString = "03/05/2011";
var format = "dd/MM/yyyy";
var date = DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture);
More information on custom Date and Time format strings can be found here.
EDIT: Try using the DateTime.FromOADate method to convert the value returned by the Range.Value2 property to a DateTime object, e.g. something like this:
var dateTime = DateTime.FromOADate(((Excel.Range)worksheet.Cells[rowCount, 3]).Value2);
DateTime.ParseExact Method converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information.
The format of the string representation must match the specified format exactly.
String dateString = "15/06/2008";
String format = "dd/MM/yyyy";
DateTime result =
DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture);
That sounds like a localization problem. Try setting your locale implicititly. For example in WPF application it's something like:
System.Threading.Thread.CurrentThread.CurrentCulture =
new System.Globalization.CultureInfo("en-US");
I have a bunch of date strings in cells that I'm pulling out such as:
No, you don't. You have a mix of strings that look like dates and dates that look like strings. This is an Excel issue, not a C# issue.
Not sure if you are creating the spreadsheet, or if you are getting it from somewhere else. But it the problem is that Excel attempt to parse text as it is entered in the cell. In this case, it is making some wrong decisions about the dates it finds.
If you enter a date like "03/05/2011", Excel will (incorrectly) parse it as March 5th, 2011, and store that as a numeric date code (40607). It then applies a date formatting to the cell (it uses m/d/yyyy on my machine).
If you enter a date like "31/05/2011", Excel can't parse it as a date, and it stores it as text.
To prove this, select the cells and go to Edit > Clear > Formats. All the "bad dates" will just show as numbers, all the rest will stay looking like dates.
You have a few choices:
Fix the data before its entered into Excel (prepend everything with a ' so its all entered as text, or make sure to create the spreadsheet on a machine that has the right date settings.)
Don't use the .Value.ToString() from Excel, just use .Text. This will ignore the bad parsing that Excel did, and should give you a consistent text value (from both types) that you can ParseExact with C#, per the other answers.
(2) is a lot easier, and if the spreadsheets already exist, may be your only choice.
The problem is because your Dates are being read as american culture or similar.
If you use the following you can specify the format you expect your dates to be in:use
DateTime result;
if(DateTime.TryParseExact("dd/MM/yyyy", out result))
{
// Got an English date
}

Categories

Resources