StrToDateDef not working
I want to convert the system date time to a specific format. My system format is dd/mm/yy which i wanted to convert to mm/dd/yyyy and so i am using StrToDateDef. I need to use StrToDateDef only because the date comes as string and if there is a string other than date i will use default date. My code is below
str := '30/01/14'; GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, FmtStngs); FmtStngs.DateSeparator := '/'; FmtStngs.ShortDateFormat := 'mm/dd/yyyy'; FmtStngs.TimeSeparator := ':'; FmtStngs.LongTimeFormat := 'hh:nn'; date := StrToDateDef(str,01/28/2013,FmtStngs);
I am expecting the date to be of '01/30/2014' but it is coming as '30/01/14'. What is that i am doing wrong?
There are several bugs in this code:
First the TFormatSettings you are passing to the StrToDateDef routine are the format settings for the string you are passing (and not for the datetime variable that comes out, more on that later).
As you are passing '30/01/14' your ShortDateFormat should be 'dd/mm/yyyy' and not 'mm/dd/yyyy'
Then the default value you are passing equals to like 1ms after midnight of 30.12.1899 (because you actually are passing 1 divided by 28 divided by 2014). Use EncodeDate(2013, 1, 28) from DateUtils.pas.
Then you are saying
I am expecting the date to be of '01/30/2014' but it is coming as '30/01/14'.
Well you are looking at a TDateTime variable and it will be formatted according to your local settings of your windows system by the debugger. Nothing more. You don't have a string but a float value (which is what TDateTime is) that is presented as string to you to make it readable.
Also I think the result should be the passed default date because the passed ShortDateFormat does not match the value of the string you are passing (trying to put 30 into the month part).