Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append TimeStamp to a File Name

People also ask

How do you add a timestamp to a script?

Ctrl / Cmd + : to insert date: 7/21/2020. Ctrl / Cmd + Shift + : to insert time: 3:25:24 PM. Ctrl / Cmd + Alt + Shift + : to insert the full timestamp: 7/21/2020 12:05:46.

How do you name a file in Linux by date?

Just use the date command with the + option. We can use backticks to capture the value in a variable. You can change the date format by using different % options as detailed on the date man page.

How do I append to a file in bash?

How to append to file in Bash. To make a new file in Bash, you normally use > for redirection, but to append to an existing file, you would use >> . Take a look at the examples below to see how it works. To append some text to the end of a file, you can use echo and redirect the output to be appended to a file.

How do you find the timestamp of a file?

You can use the stat command to see all the timestamps of a file. Using stat command is very simple. You just need to provide the filename with it. You can see all three timestamps (access, modify and change) time in the above output.


You can use DateTime.ToString Method (String)

DateTime.Now.ToString("yyyyMMddHHmmssfff")

or string.Format

string.Format("{0:yyyy-MM-dd_HH-mm-ss-fff}", DateTime.Now);

or Interpolated Strings

$"{DateTime.Now:yyyy-MM-dd_HH-mm-ss-fff}"

There are following custom format specifiers y (year), M (month), d (day), h (hour 12), H (hour 24), m (minute), s (second), f (second fraction), F (second fraction, trailing zeroes are trimmed), t (P.M or A.M) and z (time zone).

With Extension Method

Usage:

string result = "myfile.txt".AppendTimeStamp();
//myfile20130604234625642.txt

Extension method

public static class MyExtensions
{
    public static string AppendTimeStamp(this string fileName)
    {
        return string.Concat(
            Path.GetFileNameWithoutExtension(fileName),
            DateTime.Now.ToString("yyyyMMddHHmmssfff"),
            Path.GetExtension(fileName)
            );
    }
}

I prefer to use:

string result = "myFile_" + DateTime.Now.ToFileTime() + ".txt";

What does ToFileTime() do?

Converts the value of the current DateTime object to a Windows file time.

public long ToFileTime()

A Windows file time is a 64-bit value that represents the number of 100-nanosecond intervals that have elapsed since 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC). Windows uses a file time to record when an application creates, accesses, or writes to a file.

Source: MSDN documentation - DateTime.ToFileTime Method


Perhaps appending DateTime.Now.Ticks instead, is a tiny bit faster since you won't be creating 3 strings and the ticks value will always be unique also.


you can use:

Stopwatch.GetTimestamp();

You can use below instead:

DateTime.Now.Ticks