Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting string to date, and getting difference in days

Tags:

delphi

I have strings in the following format e.g. 20110201 and I want to convert it to a date in delphi, then subtract it from today to get the number of days difference.

How can I do that? Sorry for my english.

like image 933
djcis Avatar asked Jul 21 '26 22:07

djcis


2 Answers

The functions you need are Copy (to retrieve parts of your input string), StrToInt (to convert the string parts to integers), DateUtils.EncodeDate (to create a TDate from the integers), Now (to retrieve the current date as TDate) and DateUtils.DaysBetween (to get the difference between two dates in days).

I think you can figure out the rest on your own using the Delphi help for these functions.

like image 127
jpfollenius Avatar answered Jul 25 '26 21:07

jpfollenius


Use Copy to extract the 3 substrings for year, month, day. Then StrToInt to convert them into integers, then EncodeDate to turn the 3 integers into a TDateTime.

TDateTime is a float, counting whole days before the decimal point and the time at that day as the fraction after the decimal point.

In SysUtils there is a function called Date: TDateTime which returns the current date.

You can simply substract the TDateTime you parsed out of the string from the value returned by Date to get the number of days difference between them.

like image 34
Thorsten Engler Avatar answered Jul 25 '26 20:07

Thorsten Engler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!