Figuring Excel date format programmatically - excel

I have a program that gets input in the form of an excel which it reads by querying (select * into a dataset).
The excel is created by the customer.
The excel contains a date column.
The problem is, that when looking into the dataset, the date column format is sometimes like mm/dd/yyyy and sometimes dd/mm/yyyy. (1/25/1970) (25/1/1970)
I guess it depends on the locale on the machine which the excel was made.
How can my program know what is the date format in the excel?

Not sure whether your question is about output or input...
For output:
You did not mention the database type. But the rule is: make your dates the american way: mm/dd/yyyy. For Jet, I generally use Format(MyDate, ""\#dd\/mm\/yyyy\#"")
("\" is the escape character, it makes sure the next character is output "as is")
For input:
Try reading the cell format ? range("a1").NumberFormat
However on my PC, with French setup a date displayed as 15/2/2011 has a returned format = m/d/yyyy so little use here !

Related

How to standardize the text function in Excel?

=text(5/7/19,[Windows date format]) depends on the computer you are opening the Excel file from. For instance: =text(5/7/19, "mm/dd/yy") works on the company computer because that's how the windows formatted the date, but in my computer, it has to be =text(5/7/19, "dd/mm/yy") else it will return a different value and using other functions such as =datevalue(text(5/7/19, "mm/dd/yy") will return a #VALUE! error on my home computer. This is not good because it is very variable when the file is being moved around computers. How to standardize this?
So what about:
=TEXT(43592,"mm")&"/"&TEXT(43592,"dd")&"/"&TEXT(43592,"yy")
Or reference a cell where you have put your date.
Unfortunately I don't think it is possible - see the this link
Quote:
Problem: The value in the date_text argument is not in sync with the system’s date and time settings*
If your system date and time settings follow the mm/dd/yyyy format,
then a formula such as =DATEVALUE(“22/6/2000”) will result in a #VALUE! error. But the same formula will display the correct value when the system's date and time is set to dd/mm/yyyy format.
Solution: Make sure that your system’s date and time settings (both Short time and Long time) matches the date format in the
date_text argument.
I think the only solution is to make sure that your date is in the valid (i.e. recognised by the system) date format before any other function (like DATEVALUE) is applied.
It will be easy to achieve if your function is simply =text(5/7/19,[Windows date format]). You can reference your cell field (e.g. =[#Date]) and format a given cell using an "universal" date format (the ones that start with * sign).
However, if you are combining =text(5/7/19,[Windows date format]) with some other formula (e.g. when you want to display a full sentence like A very important event happened on 5/7/19) then, unfortunately, cell format won't save you here and we're out of solutions. In such case the end user would need to manually modify the date cell in order to make it recognisable.

Excel 2010 Convert text string to Full date & 24 hr time

Program: Excel 2010
Issue: External report gives me a text string, I want to convert it to Date & 24 hour time.
141221205535 needs to be:
14/12/21 20:55:35
I have tried text to columns making the result show: YMD
I have then tried using the format cells option: (custom) yy/mm/dd hh:mm:ss
* I receive a string of ######## in the Sample field in the formatting box.
I have tried also just using the date/time version, no seconds
1412212055 needs to be:
14/12/21 20:55
ideally, if possible:
20141421 2055 or 2014/14/21 20:55 I will accept
I can not alter the report as it comes through a 3rd party and I am pulling the date from a 'reference' field. The report, when downloaded, is in CSV and there is no existing formatting on the data.
I need to convert this as my sales report then needs to be sorted by date order.
Note: If I do use the seconds in the string, I get the weird looking scientific number. So i've had to reduce the digits, this isn't ideal, is there a way to avoid the scientific number whilst the process of changing 'text to date' is happening?
Thanks in advance.
I used this formula to convert:
=TEXT(A1,"2000-00-00 00\:00\:00")+0
format result cell in required format, e.g. yyyy/mm/dd hh:mm:ss
If you don't want the seconds in the underlying value you can use this version
=TEXT(LEFT(A1,10),"2000-00-00 00\:00")+0
These formulas work because TEXT function converts your value 141221205535 to a text value 2014-12-21 20:55:35, then, because that is a valid date/time format in Excel the +0 "co-erces" the text value to a serial number representing the correct date/time in Excel.....so you can then simply format the result to display any way you want.
Note that I'm assuming all dates will be in the current (21st) century.....
A formula like this would work -
=TEXT(DATE(LEFT(A1,2),MID(A1,3,2),MID(A1,5,2))+TIME(MID(A1,7,2),MID(A1,9,2),MID(A1,11,2)),"yy/mm/dd hh:mm:ss")
If your format always has 12 digits
You'll need to add the datevalue with the timevalue to get also the HMS
for example (suppose the text is in D5 cell):
=DATEVALUE(LEFT(D5,2)&"-"&MID(D5,3,2)&-MID(D5,5,2))+TIMEVALUE(MID(D5,7,2)&":"&MID(D5,9,2)&":"&RIGHT(D5,2))`

CDate to recognise Australian date format?

I have a spreadsheet I created mid-August which has a table with one column for every day since then. The column header is the day's date. The date is displayed how I want it to be displayed: "dd/mm/yyyy"
However, I have macro which needs to read these dates in order to perform its work. Because I am using a table, the dates seem to be held as text rather than as 5-digit numbers (when I set the header cells' format to "General", it remains with the "dd/mm/yyyy" format rather than changing to a 5-digit number. This wasn't a problem until the 1st of September, after which CDate (in the macro) began reading these dates as "mm/dd/yyyy"
Is there any way to make CDate recognise the Australian date format rather than the American? Or failing that, make the table headers stay as dates rather than as text? I'd rather avoid having to convert the Table back to a range, as the macro is designed to use table attributes, ListColumns etc.
UPDATE:
I've narrowed down the problem. It isn't the date, but the ListColumn.Name property. For some reason it is re-converting my date. I'm using Format() to set the date format, like so:
CreateHistoryColumn.Name = Format(headerDate, "dd/mm/yyyy")
MsgBox Day(headerDate) & "/" & Month(headerDate) & "/" & Year(headerDate)
MsgBox Format(headerDate, "dd/mm/yyyy")
MsgBox CreateHistoryColumn.Name
Where CreateHistoryCol is an object of class ListColumn. The 3 MsgBox calls display the following:
6/9/2012
06/09/2012
9/06/2012
So the Format() call formats the date correctly, but the call to ListColumn.Name serves to alter the format to "mm/dd/yyyy".
From help file:
CDate recognizes date formats according to the locale setting of your system. The correct order of day, month, and year may not be determined if it is provided in a format other than one of the recognized date settings.
I hate relying on the locale because most of the time it seems to do the opposite of what I intended, plus it makes code less portable.
I usually deal with dates as explicitly as possible:
Split your string into the various parts (year, month, day, as well as hour, minute, second if relevant)
Stick the various parts in the DateSerial function. This returns a Date type. (To that you can add the output of TimeSerial, if applicable.)
If necessary for display purposes, format this Date as appropriate using the Format function, which returns a string.
Here's a worked example.
As I showed in the update, the ListColumn.Name method was responsible for the unwanted conversion. I still don't know why, but there is any easy fix:
CreateHistoryColumn.Name = CLng(headerDate)
This forces the header to be treated as a number, and therefore it can be recognised as its proper date. I can't explain it any further than that.

Date format that is guaranteed to be recognized by Excel

We're exporting our analytics reports in various formats, among them CSV. For some clients this CSV finds it's way into Excel.
Inside the CSV file one of the columns is a Date, for example
"Start Date","Name"
"07-04-2010", "Maxim"
Excel has trouble parsing this date format, obviously depending on the Locale of the user. Is "07" is the day or the month...
Could you recommend some textual format for a Date field that excel will not have trouble parsing? I'm aiming at the most fail safe option possible. I would settle for some escape sequence that will cause excel to avoid parsing the text in the column altogether.
Thanks for helping,
Maxim.
You have two options. Go with the month as a string and the year as 4 digits, or use ISO formatting: yyyy-mm-dd.
If you format your dates as follows in the csv output, Excel will parse the content exactly as a date (other columns for realism only)
43,somestring,="03/03/2003",anotherval
55,anotherstring,="01/02/2004",finalval
so add ="{date}" and it parses as date!

Best timestamp format for CSV/Excel?

I'm writing a CSV file. I need to write timestamps that are accurate at least to the second, and preferably to the millisecond. What's the best format for timestamps in a CSV file such that they can be parsed accurately and unambiguously by Excel with minimal user intervention?
For second accuracy, yyyy-MM-dd HH:mm:ss should do the trick.
I believe Excel is not very good with fractions of a second (loses them when interacting with COM object IIRC).
The earlier suggestion to use "yyyy-MM-dd HH:mm:ss" is fine, though I believe Excel has much finer time resolution than that. I find this post rather credible (follow the thread and you'll see lots of arithmetic and experimenting with Excel), and if it's correct, you'll have your milliseconds. You can just tack on decimal places at the end, i.e. "yyyy-mm-dd hh:mm:ss.000".
You should be aware that Excel may not necessarily format the data (without human intervention) in such a way that you will see all of that precision. On my computer at work, when I set up a CSV with "yyyy-mm-dd hh:mm:ss.000" data (by hand using Notepad), I get "mm:ss.0" in the cell and "m/d/yyyy hh:mm:ss AM/PM" in the formula bar.
For maximum information[1] conveyed in the cells without human intervention, you may want to split up your timestamp into a date portion and a time portion, with the time portion only to the second. It looks to me like Excel wants to give you at most three visible "levels" (where fractions of a second are their own level) in any given cell, and you want seven: years, months, days, hours, minutes, seconds, and fractions of a second.
Or, if you don't need the timestamp to be human-readable but you want it to be as accurate as possible, you might prefer just to store a big number (internally, Excel is just using the number of days, including fractional days, since an "epoch" date).
[1]That is, numeric information. If you want to see as much information as possible but don't care about doing calculations with it, you could make up some format which Excel will definitely parse as a string, and thus leave alone; e.g. "yyyymmdd.hhmmss.000".
"yyyy-MM-dd hh:mm:ss.000" format does not work in all locales. For some (at least Danish) "yyyy-MM-dd hh:mm:ss,000" will work better.
I believe if you used the double data type, the re-calculation in Excel would work just fine.
Go to the language settings in the Control Panel, then Format Options, select a locale and see the actual date format for the chosen locale used by Windows by default. Yes, that timestamp format is locale-sensitive. Excel uses those formats when parsing CSV.
Even further, if the locale uses characters beyond ASCII, you'll have to emit CSV in the corresponding pre-Unicode Windows "ANSI" codepage, e.g. CP1251. Excel won't accept UTF-8.
"yyyy-mm-dd hh:mm:ss.000" format does not work in all locales. For
some (at least Danish) "yyyy-mm-dd hh:mm:ss,000" will work better.
as replied by user662894.
I want to add: Don't try to get the microseconds from, say, SQL Server's datetime2 datatype: Excel can't handle more than 3 fractional seconds (i.e. milliseconds).
So "yyyy-mm-dd hh:mm:ss.000000" won't work, and when Excel is fed this kind of string (from the CSV file), it will perform rounding rather than truncation.
This may be fine except when microsecond precision matters, in which case you are better off by NOT triggering an automatic datatype recognition but just keep the string as string...
So, weirdly excel imports a csv date in different ways. And, displays them differently depending on the format used in the csv file. Unfortunately the ISO 8061 format comes in as a string. Which prevents you from possibly reformatting the date yourself.
All the ones the do come in as a date... contain the entire information... but they format differently... if you don't like it you can choose a new format for the column in excel and it will work. (Note: you can tell it came in as a valid date/time as it will right justify... if it comes in as a string it will left justify)
Here are formats I tested:
"yyyy-MM-dd" shows up as a date of course when opened in excel. (also "MM/dd/yyyy" works)
"yyyy-MM-dd HH:mm:ss" default display format is "MM/dd/yyyy HH:mm" (date and time w/out seconds)
"yyyy-MM-dd HH:mm:ss.fff" default display format is "HH:mm:ss" (time only w/ seconds)
As for timezones. I have to store the UTC offset as seconds from UTC that way formulas in Excel/OpenOffice can eventually localize datetimes. I found this to be easier than storing any number that has a 0 in front of it. -0900 didn't parse well in any spreadsheet system and importing it was nearly impossible to train people to do.
Try MM/dd/yyyy hh:mm:ss a format.
Java code to create XML file.
xmlResponse.append("mydate>").append(this.formatDate(resultSet.getTimestamp("date"),
"MM/dd/yyyy hh:mm:ss a")).append("");
public String formatDate(Date date, String format)
{
String dateString = "";
if(null != date)
{
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
dateString = dateFormat.format(date);
}
return dateString;
}
I wrote my timestamps to the CSV file as yyyy-mm-dd hh:mm:ss.
In Excel 365 I create a blank workbook, go to the Data tab and choose "From Text/CSV.
A dialog opens with a preview, which weirdly leaves the first column of timestamps alone, but shows it is going to convert the second column.
You can either "Load" the data, or "Transform Data", which is what I choose.
Now you're in the "Power Query Editor" and you can massage how Excel will bring the columns in.
In my case I undo any automatic changes it made, and tell it both columns are Data Type "Date/Time" using a little button on the ribbon.
Pressing Close & Load brings it into Excel as a data source that you can sort etc.
Given a csv file with a datetime column in this format: yyyy-mm-dd hh:mm:ss
Excel shows it in this format: dd/mm/yyyy hh:mm
e.g. 2020-05-22 16:40:55 shows as 22/05/2020 16:40
This is evidently determined by the Short date and Short time format selected in Windows; for example, if I change the Short date format in Windows to yyyy-mm-dd, Excel shows 2020-05-22 16:40.
Annoyingly, I can't find any way to make Excel show the seconds automatically (I have to manually format the column in Excel). But if the csv file includes a time column in hh:mm:ss format (e.g. 16:40:55), that's what shows in Excel, including the seconds.
I would guess that ISO-format is a good idea. (Wikipedia article, also with time info)

Resources