Converting string to TDateTime

I have a string extracted from a web form that I *know* contains a
timestamp on the format:
yyyy-mm-dd hh:mm.ss  (this is the ISO standard)

Now I want to convert this to a TDateTime value and if I do this with
StrToDateTime it works just fine here in Sweden, but for some reason
it causes an error if my program is executed in the USA.. :-(

I have looked at the help for StrToDateTime and there is an overloaded
function that purportedly can be used but it is to say the least
*very* convoluted....
The FormatSettings specifier in the overloaded call is a record with
no less than 20 fields to be correctly filled in!

Isn't there some kind of function that can take a simpler format
string instead like there is when doing the opposite, example:

FormatDateTime('yyyy-mm-dd hh:nn:ss', Now);

Something like:

StringToDateTime('yyyy-mm-dd hh:nn:ss', strTimeStamp);

Any ideas?

--

Bo Berglund
Developer in Sweden
-1
Bo
4/21/2009 9:15:50 PM
embarcadero.delphi.general 4258 articles. 0 followers. Follow

13 Replies
3619 Views

Similar Articles

[PageSpeed] 37

"Bo Berglund" <bo.berglund@nospam.com> wrote in message 
news:107894@forums.codegear.com...

> I have a string extracted from a web form that I *know* contains a
> timestamp on the format:
> yyyy-mm-dd hh:mm.ss  (this is the ISO standard)
>
> Now I want to convert this to a TDateTime value and if I do this
> with StrToDateTime it works just fine here in Sweden, but for
> some reason it causes an error if my program is executed in the USA.. :-(

StrToDateTime() uses the date/time settings of the locale machine, not ISO 
or any other standards.  Since you know the formatting of the string ahead 
of time, you are better off simply parsing out the individual pieces from 
the string and then call EncodeDate() and EncodeTime() with the values.

-- 
Remy Lebeau (TeamB)
-1
Remy
4/22/2009 12:52:32 AM
Bo Berglund wrote:

> Something like:
> 
> StringToDateTime('yyyy-mm-dd hh:nn:ss', strTimeStamp);

There are a couple of functions in XSBuiltIns that may do what you want:

function DateTimeToXMLTime(Value: TDateTime; ApplyLocalBias: Boolean = True):
WideString;

and 

function XMLTimeToDateTime(const XMLDateTime: WideString; AsUTCTime: Boolean
= False): TDateTime;

Eric
-1
Eric
4/22/2009 1:41:46 AM
Eric Thorniley wrote:

> function XMLTimeToDateTime(const XMLDateTime: WideString; AsUTCTime: Boolean
> = False): TDateTime;

P.S. You might have to add the "T" in place of the space in the string. It is
optional in the ISO standard, but I think it is always there in SOAP:

So you might have to change "2009-04-11 14:23:30" to "2009-04-11T14:23:30".

If you know it is UTC time, and you want it to convert it to local time, you
may have to add a Z on the end. "2009-04-11T14:23:30Z"

Eric
-1
Eric
4/22/2009 2:19:57 AM
> {quote:title=Bo Berglund wrote:}{quote}
> I have a string extracted from a web form that I *know* contains a
> timestamp on the format:
> yyyy-mm-dd hh:mm.ss  (this is the ISO standard)
> 
> Now I want to convert this to a TDateTime value and if I do this with
> StrToDateTime it works just fine here in Sweden, but for some reason
> it causes an error if my program is executed in the USA.. :-(
> 

This works:

procedure DoTest;

var
  fs  : TFormatSettings;
  dt  : TDateTime;
  sDT : String;

begin
  sDT:='22/04/09 08:28:12';

  FillChar(fs, SizeOf(fs), 0);
  GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, fs);
  fs.ShortDateFormat := 'dd/mm/yy';
  fs.ShortTimeFormat := 'hh:mm:ss';
  fs.DateSeparator := '/';
  fs.TimeSeparator := ':';

  dt:=SysUtils.StrToDateTime(sDT,fs);

  ShowMessageFmt('sDT=%s, dt=%.4f -> sDT=%s',[sDT,dt,DateTimeToStr(dt)]);
end;

Regards,
Dag Hovden
1
Dag
4/22/2009 7:06:58 AM
On Wed, 22 Apr 2009 00:06:58 -0700, Dag Hovden <> wrote:

>> {quote:title=Bo Berglund wrote:}{quote}
>> I have a string extracted from a web form that I *know* contains a
>> timestamp on the format:
>> yyyy-mm-dd hh:mm.ss  (this is the ISO standard)
>> 
>> Now I want to convert this to a TDateTime value and if I do this with
>> StrToDateTime it works just fine here in Sweden, but for some reason
>> it causes an error if my program is executed in the USA.. :-(
>> 
>
>This works:
>
>procedure DoTest;
>
>var
>  fs  : TFormatSettings;
>  dt  : TDateTime;
>  sDT : String;
>
>begin
>  sDT:='22/04/09 08:28:12';
>
>  FillChar(fs, SizeOf(fs), 0);
>  GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, fs);
>  fs.ShortDateFormat := 'dd/mm/yy';
>  fs.ShortTimeFormat := 'hh:mm:ss';
>  fs.DateSeparator := '/';
>  fs.TimeSeparator := ':';
>
>  dt:=SysUtils.StrToDateTime(sDT,fs);
>
>  ShowMessageFmt('sDT=%s, dt=%.4f -> sDT=%s',[sDT,dt,DateTimeToStr(dt)]);
>end;
>

Thanks,
I did not want to convert the US datetime format to TDateTime, rather
I wanted a nice and consistent ISO string to be correctly converted no
matter where in the world the program happens to be running...

So I changed your code like this:

  fs.ShortDateFormat := 'yyyy-mm-dd';
  fs.ShortTimeFormat := 'hh:mm:ss';
  fs.DateSeparator := '-';
  fs.TimeSeparator := ':';

And it WORKS!
Thanks again!

--

Bo Berglund
Developer in Sweden
-1
Bo
4/22/2009 9:13:40 PM
On Tue, 21 Apr 2009 17:52:32 -0700, Remy Lebeau (TeamB)
<no.spam@no.spam.com> wrote:

>"Bo Berglund" <bo.berglund@nospam.com> wrote in message 
>news:107894@forums.codegear.com...
>
>> I have a string extracted from a web form that I *know* contains a
>> timestamp on the format:
>> yyyy-mm-dd hh:mm.ss  (this is the ISO standard)
>>
>> Now I want to convert this to a TDateTime value and if I do this
>> with StrToDateTime it works just fine here in Sweden, but for
>> some reason it causes an error if my program is executed in the USA.. :-(
>
>StrToDateTime() uses the date/time settings of the locale machine, not ISO 
>or any other standards.  Since you know the formatting of the string ahead 
>of time, you are better off simply parsing out the individual pieces from 
>the string and then call EncodeDate() and EncodeTime() with the values.

Thanks, I did not know of these functions!
I have now done as you suggested and it seems to work fine.
Have to add some try-excepts so I don't stumble on conversion errors
for malformed entry strings, though.

--

Bo Berglund
Developer in Sweden
-1
Bo
4/22/2009 9:43:13 PM
Bo,

> Have to add some try-excepts so I don't stumble on conversion errors
> for malformed entry strings, though.

Generally, there are Try* variations of the Date-Time routines that do
not raise exceptions.

- Brian
-1
Brian
4/22/2009 10:05:22 PM
> {quote:title=Bo Berglund wrote:}{quote}
> I did not want to convert the US datetime format to TDateTime, rather

No, that was just the format that happened to be in my code.

I forgot to mention this: the line "FillChar(fs, SizeOf(fs), 0);" is necessary because it seems that GetLocaleFormatSettings doesn't completely fill the TFormatSettings structure so if you try this without the FillChar you may get all kinds of strange exception errors.

Anyway, nice to hear that it works.

Regards,
Dag Hovden
Originally from Sweden but now Developer in The Netherlands :-)
-1
Dag
4/23/2009 11:39:38 AM
I don't mean to hi-jack this thread but it touches on a problem I
have.  Some of my users like to set the short date format to
dd-MMM-yy.  This helps them avoid the confusion between dd-mm and
mm-dd i.e. is 2-3-09 March 2, 2009 or February 3, 2009?  I have tried
TryStrToDate, but it reports that dates like 24-apr-09 has being
invalid.

Any suggestions?

Luke
On Wed, 22 Apr 2009 00:06:58 -0700, Dag Hovden <> wrote:

>> {quote:title=Bo Berglund wrote:}{quote}
>> I have a string extracted from a web form that I *know* contains a
>> timestamp on the format:
>> yyyy-mm-dd hh:mm.ss  (this is the ISO standard)
>> 
>> Now I want to convert this to a TDateTime value and if I do this with
>> StrToDateTime it works just fine here in Sweden, but for some reason
>> it causes an error if my program is executed in the USA.. :-(
>> 
>
>This works:
>
>procedure DoTest;
>
>var
>  fs  : TFormatSettings;
>  dt  : TDateTime;
>  sDT : String;
>
>begin
>  sDT:='22/04/09 08:28:12';
>
>  FillChar(fs, SizeOf(fs), 0);
>  GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, fs);
>  fs.ShortDateFormat := 'dd/mm/yy';
>  fs.ShortTimeFormat := 'hh:mm:ss';
>  fs.DateSeparator := '/';
>  fs.TimeSeparator := ':';
>
>  dt:=SysUtils.StrToDateTime(sDT,fs);
>
>  ShowMessageFmt('sDT=%s, dt=%.4f -> sDT=%s',[sDT,dt,DateTimeToStr(dt)]);
>end;
>
>Regards,
>Dag Hovden
---
Luke Miller
ResCorSoft, Inc.

"Feliz es el hombre que ha hallado sabiduría, 
 y el hombre que consigue discernimiento"
-1
Luke
4/24/2009 4:34:07 PM
Luke Miller wrote:

> I don't mean to hi-jack this thread but it touches on a problem I
> have.  Some of my users like to set the short date format to
> dd-MMM-yy.  This helps them avoid the confusion between dd-mm and
> mm-dd i.e. is 2-3-09 March 2, 2009 or February 3, 2009?  I have tried
> TryStrToDate, but it reports that dates like 24-apr-09 has being
> invalid.

The functions available in the Delphi RTL cannot convert strings
containing month names, whether they are abbreviated or not. You would
have to write a parser for such formats yourself. It is possible to get
the abbreviated and full names for the months from Windows, for the
current locale. In fact the Sysutils unit does that for you, see the
ShortMonthNames and LongMonthNames variables.


-- 
Peter Below (TeamB)  
Don't be a vampire (http://slash7.com/pages/vampires), 
use the newsgroup archives :
http://www.tamaracka.com/search.htm
http://groups.google.com
-1
Peter
4/24/2009 5:20:59 PM
Hello,

> have.  Some of my users like to set the short date format to
> dd-MMM-yy.  This helps them avoid the confusion between dd-mm and
> mm-dd i.e. is 2-3-09 March 2, 2009 or February 3, 2009?  I have tried
> TryStrToDate, but it reports that dates like 24-apr-09 has being
> invalid.

Try to use the VarToDateTime function

-- 
With best regards, Mike Shkolnik
http://www.scalabium.com
-1
Mike
4/24/2009 5:57:43 PM
Luke Miller wrote:

> I don't mean to hi-jack this thread but it touches on a problem I
> have.  Some of my users like to set the short date format to
> dd-MMM-yy.  This helps them avoid the confusion between dd-mm and
> mm-dd i.e. is 2-3-09 March 2, 2009 or February 3, 2009?  I have tried
> TryStrToDate, but it reports that dates like 24-apr-09 has being
> invalid.
> 
> Any suggestions?

Use the user preference only to present dates, for storage use your own
fixed format preferable an ISO standard something like yyyymmddThhmm.

Also see http://en.wikipedia.org/wiki/ISO_8601

-- 
Pieter

"Nothing is wrong with California that a rise in the ocean level
 wouldn't cure."
 -- Ross MacDonald (1915-1983)
1
Pieter
4/24/2009 8:58:55 PM
Luke Miller wrote:

> I don't mean to hi-jack this thread but it touches on a problem I
> have.  Some of my users like to set the short date format to
> dd-MMM-yy.  This helps them avoid the confusion between dd-mm and
> mm-dd i.e. is 2-3-09 March 2, 2009 or February 3, 2009?  I have tried
> TryStrToDate, but it reports that dates like 24-apr-09 has being
> invalid.

The functions available in the Delphi RTL cannot convert strings
containing month names, whether they are abbreviated or not. You would
have to write a parser for such formats yourself. It is possible to get
the abbreviated and full names for the months from Windows, for the
current locale. In fact the Sysutils unit does that for you, see the
ShortMonthNames and LongMonthNames variables.


-- 
Peter Below (TeamB)  
Don't be a vampire (http://slash7.com/pages/vampires), 
use the newsgroup archives :
http://www.tamaracka.com/search.htm
http://groups.google.com
0
Peter
4/25/2009 7:45:49 AM
Reply:

Similar Artilces:

Best Place to get help on converting Delphi 2007 string to Delphi 2009
Where is the best place to get help on converting Delphi 2007 strings to Delphi 2009? The most common problem getting Delphi 7-Delphi 2007 components to compile seems to be caused by the new Unicode strings in Delphi 2009. It would be great if there was some place to go to get help with this. Maybe there should be a new group for String conversion where developers could ask short questions about conversion. For example: Delphi 7 - Delphi 2007 CharArrayPtr = ^CharArray; CharArray = array[0..MaxInt-1] of Char; Compiles Delphi 2009 CharArrayPtr = ^CharArray; CharArray ...

Convert string to string array.
Hi, We have a string array argument in datawindow object for 'IN' sql statement. Our user enter a string in a single line edit. How to convert the string to a string array for the argument of datawindow? ex. user input : 'A', 'B', 'C' => str_arr[]={'A', 'B', 'C'} dw_1.retrieve(str_arr) Thanks in advance. Take a look at the n_cst_string object in the pfc. It has a method called of_ParseToArray that does exactly what you're looking for. It's a pretty simple task to 'port' the code ...

How to convert a String into a UTF8 String
Hello! I want to convert a normal String into a UTF8 String for example:myString = BüromyUTF8String = Büros  I dont know how to do this. In PHP you can do this with myUTF8String = utf8_encode(myString) Thank you for all hints! try this string test ="ÁÉÍÓÚ áéíóú àèìòù äëïöü Ññ €"; byte[] a= System.Text.Encoding.UTF8.GetBytes(test); string test2= System.Text.Encoding.UTF8.GetString(a);  greetingsBest Regards,Sebastián DopicoBlog Desarrollador Thank you Sebastián! If I make it like that - test2 looks the same as test.But I think my problem is solved. (Someone tol...

Delphi XE convert string character to Ansichar
Hi Is there a function for converting a character in a string (unicode) to an ansichar. I am upgrading some very old programs to XE that work with characters and their ordinal values. I have just been type casting them with ansistring or ansichar, but some characters are giving incorrect results. For example var s : string; begin s := '€'; // character is hex 80 or 128 decimal showmessage(inttostr(ord(s[1]))); showmessage(inttostr(ord(ansichar(s[1])))); The above give two different answers (I can understand the first), but not why the second gives the inc...

Converting a list of string into string
When I try the following code in Prism I get the error "Error 8 (CE15) Type mismatch, cannot assign array of System.String to System.String " ***************************************************************** var mobileNumberList :List<string> mobNumberArray :string Begin mobileNumberList.add('1234567890'); mobNumberArray := mobileNumberList.ToArray();//error here end; *************************************************************** What needs to be done to convert an array of strings to a string Venkatesh Venkatesh VT a écrit : > When I...

convert octet string to string
I'm trying to use IDM 3.5.1 provision an AD environmnet with users from eDir. We wanna provision as much info as possible, but one attribute gives us headaches. This is an auxiliary attribute associated with each user in eDir that has it's syntax set to octet string. Problem is we need to provision this over to another attribute in AD that uses string as its syntax. Is thee a way through XPath or ECMA script to have the value converted during the provisioning? I've no experience with either XPath or ECMA so please be detailed in your replies. Thx -- jdoeconsu...

Hoew to convert to/from Delphi 32 TDateTime and .NET Datetime
Hi If we have code that uses Tdatetime, and convert the code to .Net, what should we use: 1. as type Tdatetime replacement? 2. to marshal .Net datetime to TDateTime? Thanks very much -- E.P. Enrico Pergola wrote: > Hi > > If we have code that uses Tdatetime, and convert the code to .Net, what should we use: > 1. as type Tdatetime replacement? > 2. to marshal .Net datetime to TDateTime? > Thanks very much > You can start using the type TDateTime from ShineOn. But after you have a compiling and working code base, and after you created enough test cas...

Convert UPPERCASE string to Upper-Lower Case (ie. THIS IS MY STRING -> This Is My String)
I recently had the need to convert an all capitalized string to upper/lower case, but couldn't find anything to do it in XSLT 1.0.  If it helps anyone out, I wrote the following:   Call it using: <xsl:template match="Ads">  <xsl:call-template name="ToUpperLowerCase">   <xsl:with-param name="inputString" select="YOURSTRINGHERE"/>   <xsl:with-param name="index" select="0"/>   <xsl:with-param name="loopCount" select="st...

Type converter
I have a custom type converter on a class that is working fine on the "ToString()". I have the reverse coded into the CanConvertFrom(), but I can't seem to find a way to create the object from a String. Am I missing something here? Simply override the ConvertFrom method on your TypeConverter class. So take its input string value, process it, and have the ConvertFrom method instantiate and return an instance of your class.Hope that helps,WimWim Hollebrandse---http://www.zealandit.com         public override object ConvertFrom(ITypeDescriptorCont...

converting string to integer, subtracting strings.
Hi,  I have a textbox into which the user will enter a number I then have button that when the user clicks, the number taken from the textbox will be subtracted by one or more(depending on the users situation) and displayed in a label.   The problem i am having at the moment is that when i attempt to do this an error comes up saying that "the operator '-' cannot be used with string or int". String Score1 = txtScore1.Text: String netScore1;   netScore1 = Score1 - 1; lblNetScore1.Text = netScore1;   I have ...

Converting from Delphi 2005 to Delphi XE5
I have developed a number of Windows applications in Delphi 2005. I recently purchased Delphi XE5. I have started by trying to compile an existing 2005 application. I am getting a 7 errors about FMXTeeEditor. [dcc32 Error] E1026 File not found: 'FMXTee.Editor.Brush.fmx' Not able to find a solution to this. Any help greatly appreciated. Did you open every form before compiling? The old forms get updated with new properties when they are opened. I would make a copy of the old project before doing any of this. maybe you have links to the older tchart files....i.e its not usi...

converting delphi code to delphi .NET
Hi,I'm looking at converting quite a bit of old delphi code to delphi .NET .  I'm wondering can it be converted to VB.NET for certain ?  Or perhaps there are some unsupported functions etc in delphi and I should keep the code delphi ?  There are about 10,000 lines of code.   Anyone brave enough to take an estimate on how long it would take to convert 10,000 lines ?is going from delphi to delphi.NET smooth ?   Would going to another language cause complications ?Thanks! mike123   Mike123,   Sorry I can not help, however, I have the s...

Convert Unicode string to Readable String
Novell Identity Manager 3.5.1 RedHat Linux enterprise edition. SOAP IDM driver.. When I query on an attribute "firstName" from IDM, the application returns value on that atrribute as the "English\u00c6". It looks like the string comes as a Unicode string.. I need help to reformat that value so that it can be readable for my rules in my driver.. Any help guys? Regards, M. -- love anything that talks binary! ------------------------------------------------------------------------ On Fri, 21 May 2010 08:26:01 +0000, belaie wrote: >...

Convert Object/String to a Base64 String
The function below converts a normal string to a Base64 string. This can come in pretty handy ;) public static string getBase64Encoded(string inString) { byte[] inData; char[] charArr; //System.IO.StringReader sr = new System.IO.StringReader(inString); //sr.Read(inData, 0, inString.Length); charArr = inString.ToCharArray(); inData = new byte[charArr.Length]; for(int i = 0; i < charArr.Length; i++) { inData[i] = (byte)charArr[i]; } return System.Convert.ToBase64String(inData, 0 , inData.Length); } ...

Web resources about - Converting string to TDateTime - embarcadero.delphi.general

PastBook’s Filepicker.io Integration Eases Process Of Converting Facebook Content To Books
PastBook , one of several companies that allow Facebook users to publish their content on the social network in actual books , announced the ...

Facebook No Longer Converting Groups Into Pages
Back when Facebook first launched Facebook Pages, many businesses and brands who had built up substantial audiences in their Facebook Groups ...

Zwartz Laminating-Converting B.V. on the App Store on iTunes
Get Zwartz Laminating-Converting B.V. on the App Store. See screenshots and ratings, and read customer reviews.


"Occupier" Thanked Former Soviet Citizen for "Converting" Him to Capitalism, Pro-Israel, Pro-USA - YouTube ...
May Day Demonstration on Union Square in New York City Zionism & Birth of Modern Israel in 1948: Former Soviet Citizen Pays Tribute to Ben-Gurion ...

Click go fears of converting print files
Is there a way to convert a print queue item to a .RTF or .PDF file? I like to save or email them. - The Sydney Morning Herald

Sudanese woman ordered to hang under sharia law for converting to Christianity gives birth
Khartoum, Sudan: A Christian Sudanese woman sentenced to hang for apostasy has given birth in jail, a Western diplomat said on Tuesday.

Imams warn against radicalism to Aboriginal inmates converting to Islam
The prison system has enlisted the help of ASIO to crack down on radicalisation behind bars amid revelations that Aboriginals are converting ...

Converting the world's companies one by one - The Science Show - ABC Radio National (Australian Broadcasting ...
Image: Trucks carrying logs make their way up a road in Jambi, Indonesia. A vast area of the Sumatran forest, and orangutan habitat, is being ...

Converting Churches Into Homes Is The Latest Hollywood Trend
You don't have to be a believer to be moved by the beauty of a church.

Resources last updated: 12/16/2015 7:35:32 PM