Skip to content

Instantly share code, notes, and snippets.

@Glutexo
Created September 14, 2014 12:48
Show Gist options
  • Save Glutexo/78c170e2e314f0eacc1a to your computer and use it in GitHub Desktop.
Save Glutexo/78c170e2e314f0eacc1a to your computer and use it in GitHub Desktop.
AppleScript to get current date and time (YYYY-MM-DD HH:MM:SS). Usable as a Text Service in Mac OS X.
(*
The zero_pad function taken from:
http://www.nineboxes.net/2009/10/an-applescript-function-to-zero-pad-integers/
*)
on zero_pad(value, string_length)
set string_zeroes to ""
set digits_to_pad to string_length - (length of (value as string))
if digits_to_pad > 0 then
repeat digits_to_pad times
set string_zeroes to string_zeroes & "0" as string
end repeat
end if
set padded_value to string_zeroes & value as string
return padded_value
end zero_pad
on run
set now to (current date)
set result to (year of now as integer) as string
set result to result & "-"
set result to result & zero_pad(month of now as integer, 2)
set result to result & "-"
set result to result & zero_pad(day of now as integer, 2)
set result to result & " "
set result to result & zero_pad(hours of now as integer, 2)
set result to result & ":"
set result to result & zero_pad(minutes of now as integer, 2)
set result to result & ":"
set result to result & zero_pad(seconds of now as integer, 2)
return result
end run
@Jorsta
Copy link

Jorsta commented Aug 19, 2025

This kan be done in many easier ways. Here is a oneliner:

do shell script "date '+%Y-%m-%d %H:%M:%S'

@Glutexo
Copy link
Author

Glutexo commented Aug 20, 2025

@Jorsta Wow! My solution is, however, pure AppleScript.

@Jorsta
Copy link

Jorsta commented Aug 21, 2025

Right! This is basically doing the same thing as your script, but shorter.

on run
	set now to (current date)
	set dateString to "" & year of now & "-" & my twoDigit(month of now as integer) & "-" & my twoDigit(day of now) & space & my twoDigit(hours of now) & ":" & my twoDigit(minutes of now) & ":" & my twoDigit(seconds of now)
	return dateString
end run

on twoDigit(theValue)
	if (count theValue as string) is 1 then set theValue to "0" & theValue
	return theValue
end twoDigit

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment