6

How can I show date in YYYY-MM-DDTHH:MM:SS+ZZZZ format in LINUX? I need to write the creation date of a file say file1 in another file say file2 in given format. Help me to achieve this.

4 Answers4

13

The date format you are referring to is ISO 8601. Use the -I option to the date command to format dates according to this format (the s specifies precision up to integral seconds):

$ date -Is
2013-10-08T10:48:03+0300

To obtain the last modification time of a file (in seconds since the epoch), use the %Y format specifier with the stat command:

$ stat -c %Y file1
1378818806

Combining these two, use date -d to format the output of stat -c:

$ date -Is -d @`stat -c %Y file1`
2013-09-10T16:13:26+0300

So this is the statement that does what you need:

$ date -Is -d @`stat -c %Y file1` > file2
zwets
  • 12,354
  • Too bad none of date manual page, info documentation or --help output mention the -I option. I finally found it here https://www.gnu.org/software/coreutils/manual/html_node/Options-for-date.html and of course in the source code too. – jlliagre Oct 09 '13 at 20:03
  • 1
    @jlliagre man date (from coreutils 8.20 on Ubuntu 13.04) shows this option: -I[TIMESPEC],--iso-8601[=TIMESPEC] output date and time in ISO 8601 format. – zwets Oct 10 '13 at 05:36
  • Thanks, the documentation was just lagging then, I'm using 12.10. – jlliagre Oct 10 '13 at 14:22
5

You can display a date that way with this command:

$ date +%Y-%m-%dT%H:%M:%S%z
2013-10-08T07:38:45+0200

Many file systems do not store a file creation date so there is not always a method to get it. If the file has never been modified since its creation, this would work:

$ date -r file1 +%Y-%m-%dT%H:%M:%S%z > file2
$ cat file2
2013-10-08T07:32:52+0200
jlliagre
  • 5,833
1

Does this help you?

ls -c -l file1 --time-style="+%Y-%m-%dT%H:%M:%S%z" > file 2
MadMike
  • 4,244
  • 8
  • 28
  • 50
1

Combining my previous answer and that of @jlliagre, the most concise way to do what you want is:

date -Is -r file1 > file2
zwets
  • 12,354