开发者

Timestamp on Windows similar to Unix timestamp and file manipulations

开发者 https://www.devze.com 2022-12-27 12:13 出处:网络
I am aware that linux has timestamp info available to prog. langs. which is very handy. I m developing a program and i need to append date time to the created file. and it should be unique.

I am aware that linux has timestamp info available to prog. langs. which is very handy.

I m developing a program and i need to append date time to the created file. and it should be unique.

Later on I want to parse the files, but i want to parse the latest one only.

Is there such option in .net like timestamp in *nix systems?

A开发者_运维问答ny examples out there?

Thanks.


You could use the Ticks property of a DateTime structure. It's not compatible with the UNIX timestamp, but it can be used to return a long (Int64) that represents the date and time with a precision of one ten-millionth of a second. E.g.

DateTime.Now.Ticks

At time of writing this returns the value of 634074617762026300

You can convert ticks back to a DateTime in the constructor. E.g.

DateTime date = new DateTime(634074617762026300);


If you want timestamps from files, look at the FileInfo class. If you want to add the UNIX timestamp to the file (perhaps to the file name or as you said, appended to the end), this function gets you a UNIX timestamp:

public static int UnixTimestamp()
{
    var utcEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
    var utcNow = DateTime.UtcNow;
    var span = utcNow - utcEpoch;
    return (int)span.TotalSeconds;
}


"Unique" and file names based timestamps are contradictory requirements. It falls apart when the machine gets faster. Workarounds that try to check if the file already exists fall apart when more of one instance of your program runs. Only Path.GetTempFileName() can guarantee a completely unique name. Use FileInfo.CreationTimeUtc to find the last one.

0

精彩评论

暂无评论...
验证码 换一张
取 消