Time string comparison in XPath 1.0

2019-09-03 15:30发布

问题:

I've got this comparison in XPath1.0:

number(substring(translate(translate(translate(@pub-date,'-',''),':',''),' ','') ,5,4)+substring(translate(translate(translate(@pub-date,'-',''),':',''),' ',''),2,3)+substring(translate(translate(translate(@pub-date,'-',''),':',''),' ',''),0,2)+substring(translate(translate(translate(@pub-date,'-',''),':',''),' ',''),9,6)) > number(substring(translate(translate(translate(@pub-date2,'-',''),':',''),' ','') ,5,4)+substring(translate(translate(translate(@pub-date2,'-',''),':',''),' ',''),2,3)+substring(translate(translate(translate(@pub-date2,'-',''),':',''),' ',''),0,2)+substring(translate(translate(translate(@pub-date2,'-',''),':',''),' ',''),9,6))

This compares @pub-date and @pub-date2. These Strings have this format: dd-mm-yyyy hh:mm:ss.

The problem is: is @pub-date = "30-07-2014 23:59:59" and @pub-date2 = "30-08-2014 00:00:00", @pub-date is considered bigger than @pub-date2. What's wrong with this XPath?

回答1:

What you are doing is summing up all the numbers in the date, so of course a date like 01-01-0000 23:59:59 will result in a higher value than 02-01-0000 00:00:00.

What you have to do is get the date string in the order YearMonthDayTime that way you get a number that will be higher every second.

number(concat(substring(@pub-date,7,4),
substring(@pub-date,4,2),
substring(@pub-date,1,2),
translate(substring(@pub-date,12,8),':',''))) >
number(concat(substring(@pub-date-2,7,4),
substring(@pub-date-2,4,2),
substring(@pub-date-2,1,2),
translate(substring(@pub-date-2,12,8),':','')))

This will compare 20140730235959 with 20140830000000



回答2:

Firstly, the expression

translate(translate(translate(@pub-date,'-',''),':',''),' ','') 

could be written a lot more concisely as

translate(@pub-date,'-: ','')

Secondly, and more importantly, the arguments to substring() are wrong. If you want to pull out the Y, M, and D from 30072014 then you want (5,4), (3,2), and (1,2) whereas this expression grabs (5,4), (2,3), and (0,2).