Date Formatting With Command-Line Tools

PHP:

formatDate("Y-m-d", current date)

on formatDate(theFormat, theDate)
	-- theDate should be an AppleScript date object
	do shell script "/usr/bin/php -r 'echo date($argv[1], strtotime($argv[2]));' " & ¬
		quoted form of theFormat & " " & quoted form of (theDate as Unicode text)
end formatDate

See also: http://php.net/date

Edit: http://php.net/strtotime

Hi Bruce,

I like it, but apparently it works only on systems with english date format settings.
With my german date format settings I get the result 1970-01-01

Ruby:

formatDate("%Y-%m-%d", current date)

on formatDate(theFormat, theDate)
	-- theDate should be an AppleScript date object
	try
		do shell script "/usr/bin/ruby -e 'require \"parsedate\"; puts Time.local(*ParseDate.parsedate(ARGV[1])).strftime(ARGV[0])' " & ¬
			quoted form of theFormat & " " & quoted form of (theDate as Unicode text)
	on error
		-- The date could not be parsed
		return false
	end try
end formatDate

See also: http://www.ruby-doc.org/core/classes/Time.html#M000297

Edit: This also requires a US English date format.

I’m sorry, same problem, I get this error message (with the Ruby version)

-e:1:in `local’: no implicit conversion from nil to integer (TypeError)
from -e:1

Apparently so; I’ve edited my first post.

How does this work for you?

formatDate("Y-m-d", (current date) as «class isot» as string)

on formatDate(theFormat, theDate)
	-- Example for theDate: "2007-10-23T17:54:23"
	do shell script "/usr/bin/php -r 'echo date($argv[1], strtotime($argv[2]));' " & ¬
		quoted form of theFormat & " " & quoted form of theDate
end formatDate

actually it works, but I have an offset of +9 hours in the result (now we have 00:03:00
2007-10-24-09-03-00

Ruby with isot:

formatDate("%Y-%m-%d", (current date) as «class isot» as string)

on formatDate(theFormat, theDate)
	-- Example for `theDate`: "2007-10-23T17:54:23"
	try
		do shell script "/usr/bin/ruby -e 'require \"parsedate\"; puts Time.local(*ParseDate.parsedate(ARGV[1])).strftime(ARGV[0])' " & ¬
			quoted form of theFormat & " " & quoted form of theDate
	on error
		-- The date could not be parsed
		return false
	end try
end formatDate

Ruby works fine also with H-M-S

formatDate("%Y-%m-%d-%H-%M-%S", (current date) as «class isot» as string)

Good. :slight_smile:

Not good. :confused: I actually have a +3 offset here.

The offset was gone after I removed the “T” from the isot string.

This works with the php version


formatDate("Y-m-d_H-i-s", current date)

on formatDate(F, D)
	tell D as «class isot» as string to set theDate to text 1 thru 10 & " " & text 12 thru -1
	do shell script "/usr/bin/php -r 'echo date($argv[1], strtotime($argv[2]));' " & ¬
		quoted form of F & " " & quoted form of theDate
end formatDate

I don’t have this problem with PHP 5.2.4. (Which I mistakenly tested with when I first posted.)

PS: After testing both php and ruby verisons, I prefer the php one because the parameters are easier to use (for me)