Lazarus

Programming => General => Topic started by: Jvan on October 28, 2020, 12:45:09 am

Title: How to change the format of a date string
Post by: Jvan on October 28, 2020, 12:45:09 am
If I have '27/10/2020' and I want it to be '2020-10-27', so how?
Title: Re: How to change the format of a date string
Post by: jamie on October 28, 2020, 02:56:46 am
https://www.freepascal.org/docs-html/rtl/sysutils/formatdatetime.html

look for examples using that etc.
Title: Re: How to change the format of a date string
Post by: bytebites on October 28, 2020, 05:06:53 am
Code: Pascal  [Select][+][-]
  1.  
  2. var d:string;
  3. begin
  4.   d:= '27/10/2020';
  5.   writeln(d[7..11]+'-'+d[4..5]+'-'+d[1..2]);
  6. end;
  7.  
Title: Re: How to change the format of a date string
Post by: PascalDragon on October 28, 2020, 09:15:08 am
https://www.freepascal.org/docs-html/rtl/sysutils/formatdatetime.html

look for examples using that etc.

And in addition to that ScanDateTime (https://www.freepascal.org/docs-html/rtl/dateutils/scandatetime.html). You convert your date string to a TDateTime with the help of ScanDateTime and then convert it back to a string using FormatDateTime.

Alternatively you can use StrToDateTime (https://www.freepascal.org/docs-html/rtl/sysutils/strtodatetime.html) and DateTimeToStr (https://www.freepascal.org/docs-html/rtl/sysutils/datetimetostr.html) though in both cases you should supply the FormatSettings parameter with the correct formats.
Title: Re: How to change the format of a date string
Post by: cdbc on October 28, 2020, 01:17:30 pm
Hi
Would this be of any help???:
Code: Pascal  [Select][+][-]
  1. function bcDateToStr(const aDate: TDateTime): string;
  2. begin // LongDateFormat: 'dd" "mmmm" "yyyy';
  3. //  DateTimeToString(Result,FormatSettings.LongDateFormat,aDate,FormatSettings);
  4.   DateTimeToString(Result,'dd"."mm"."yyyy',aDate,FormatSettings);
  5. end;
  6.  
Regards Benny
Title: Re: How to change the format of a date string
Post by: wp on October 28, 2020, 01:31:50 pm
Try this:
Code: Pascal  [Select][+][-]
  1. program Project1;
  2.  
  3. uses
  4.   SysUtils, DateUtils;
  5.  
  6. function ChangeDateFormat(ADateStr, ASourcePattern, ADestPattern: String): String;
  7. var
  8.   dt: TDateTime;
  9. begin
  10.   dt := ScanDateTime(ASourcePattern, ADateStr);
  11.   Result := FormatDateTime(ADestPattern, dt);
  12. end;
  13.  
  14. const
  15.   d = '27/10/2020';
  16. begin
  17.   WriteLn(d, ' ---> ', ChangeDateFormat(d, 'dd"/"mm"/"yyyy', 'yyyy-mm-dd'));
  18.   ReadLn;
  19. end.

The source pattern parameter is needed since otherwise it will not be clear whether a number refers to the day or to the month. Note also that the slash must be quoted in the source pattern because otherwise the slash would be replaced by the DateSeparator of the FormatSettings, and I did not want to add another parameter.
TinyPortal © 2005-2018