Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find the current time and date at compilation time in .net/C# application?

Tags:

c#

clr

build

I want to include the current time and date in a .net application so I can include it in the start up log to show the user what version they have. Is it possible to retrieve the current time during compilation, or would I have to get the creation/modification time of the executable?

E.g.

Welcome to ApplicationX. This was built day-month-year at time.

like image 601
Nick Avatar asked Jun 09 '09 17:06

Nick


People also ask

How to get current time and date in C#?

DateTime now = DateTime. Now; With the Now property of the DateTime , we get the current date and time in local time. Console.

How to input DateTime in C#?

If you want to set both the date and the time, all you have to do is add it so: DateTime dateTime = new DateTime(2016, 7, 15, 3, 15, 0); Now, the time has been set to 3:15 AM. DateTime also has a property called Today that returns the current date with time set to 0:00:00.


1 Answers

If you're using reflection for your build number you can use that to figure out when a build was compiled.

Version information for an assembly consists of the following four values:

  1. Major Version
  2. Minor Version
  3. Build Number
  4. Revision

You can specify all the values or you can accept the default build number, revision number, or both by using an asterisk (*). Build number and revision are based off Jan 1, 2000 by default.

The following attribute will set Major and minor, but then increment build number and revision.

[assembly: AssemblyVersion("5.129.*")]

Then you can use something like this:

public static DateTime CompileTime
{
   get
   {
      System.Version MyVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
      // MyVersion.Build = days after 2000-01-01
      // MyVersion.Revision*2 = seconds after 0-hour  (NEVER daylight saving time)
      DateTime compileTime = new DateTime(2000, 1, 1).AddDays(MyVersion.Build).AddSeconds(MyVersion.Revision * 2);                
      return compileTime;
   }
}
like image 168
Sam Trost Avatar answered Oct 12 '22 11:10

Sam Trost