4

zsh builtin print has option -P to perform prompt expansion, and this could be used to get the current time. I wonder if there are other ways to achieve this? And how about for other shells?

mklement0
  • 382,024
  • 64
  • 607
  • 775
oxnz
  • 835
  • 6
  • 16
  • Do you mean, time from timestamp? – sjsam Dec 01 '15 at 08:09
  • yes, but there seems no other way but invoke external command, are there? – oxnz Dec 01 '15 at 08:55
  • Don't know what the other guys are talking about here. You don't know a way doesn't mean there isn't a way. Sure there is. `zmodload zsh/datetime && print $EPOCHSECONDS`. – 4ae1e1 Dec 01 '15 at 10:41
  • @4ae1e1 : I took my answer back thank you for ponting that out. I did have a look `strftime` but i never knew that it is incorporated to newer bash shells. – sjsam Dec 01 '15 at 11:23
  • @sjsam No problem, I also didn't know that until several weeks ago. Sorry about my strong words, but I was slightly annoyed by the obnoxious atmosphere in this question. Seeking a native solution seems legit to me. – 4ae1e1 Dec 01 '15 at 11:25
  • If you want a single approach portable between all the tagged shells, then you're going to be disappointed. Both bash and zsh can do this (I don't know about tcsh -- but don't use it, anyhow), but there's no such capability specified in POSIX sh, so you won't find a solution portable across all available shells. – Charles Duffy Dec 01 '15 at 14:52

1 Answers1

6

bash 4.2 introduced a new format specifier for the printf builtin. With no argument, it prints the current time in the given format.

# Default is the current time
$ printf "%()T\n"
8:30 
# Current year
$ printf "%(%Y)T\n"
2015

An integer argument is treated as the number of seconds since Jan 1, 1970.

$ printf "%(%Y-%m-%d)T\n" 1234567890
2009-02-13

The same works in (some versions of) ksh, from which bash presumably borrowed it.

chepner
  • 497,756
  • 71
  • 530
  • 681