Search code examples
bashdatetimestampzshls

How to convert ZSH ls timestamps to %Y-%m-%d?


Anyone know how to convert zsh ls timestamps to %Y-%m-%d?

From this (zsh):

host1% ls -lrt | tail -1

-rw-r----- 1 user group 4802 Mar 21 15:41 get.csv

To this (bash):

user@host1:/home/user> ls -ltr | tail -1

-rw-r----- 1 user group 4802 2013-03-21 15:41 get.csv

Solution

  • This can work:

    $ date -d "Mar 21 15:41" "+%Y-%m-%d %H:%M"
    2013-03-21 15:41
    

    Where with -d you give the script the date you want to parse and each variable within "+ ..." stands for:

    • Y year
    • m month
    • d day
    • H hour (24h)
    • M minute

    To get Mar 21 15:41 from the initial line (the one coming from ls -l), you can

    $ echo "-rw-r----- 1 user group 4802 Mar 21 15:41 get.csv" | cut -d' ' -f6,7,8
    Mar 21 15:41
    

    As indicated in comments by the OP, the -r (display the last modification time of FILE) parameter can be useful for this purpose, as it indicates the file from which we want to know the info:

    $ date -r name_of_file "+%Y-%m-%d %H:%M"