2016-03-30 28 views
0

我想當前的日期返回到我的事件記錄器,我已經試過這樣:Datetime.utc返回1-1-0001 00:00:00在事件查看器

public class LogDate 
{ 
    protected DateTime localDate { get; set; } 

    public LogDate() 
    { 
     localDate = DateTime.Now; 

    } 
} 

public class Eventlog : LogDate 
{ 
    public void logEvent(string answer) 
    { 

     this.localDate = new DateTime(); 


     try 
     { 
      string sSource; 
      string sLog; 
      string sEvent; 

      sSource = "dotNET Sample App"; 
      sLog = "filmdatabase"; 
      sEvent = this.localDate + answer; 

不知何故,當我嘗試這個,它返回1-1-0001 00:00:00。而不是實際的時間。

+0

順便說一句,有沒有'DateTime.UtcNow'在你的代碼。 –

回答

3

您指定this.localDate又一個新DateTime

this.localDate = new DateTime(); 

1-1-0001 00:00:00new DateTime()默認值。要修復它,請使用this.localDate,而不要將其重新分配爲new DateTime()

public class Eventlog : LogDate 
{ 
    public void logEvent(string answer) 
    { 

     //this.localDate = new DateTime(); //remove this  

     try 
     { 
      string sSource; 
      string sLog; 
      string sEvent; 

      sSource = "dotNET Sample App"; 
      sLog = "filmdatabase"; 
      sEvent = this.localDate.ToString() + " " + answer; //use it directly as you have initialized that in your constructor 

直接使用它作爲你一直在構造函數初始化它:

public class LogDate 
{ 
    protected DateTime localDate { get; set; } 

    public LogDate() 
    { 
     localDate = DateTime.Now; 

    } 
} 
+0

謝謝,即時通訊如此愚蠢,以至於我沒有看到 –

+0

@LarsKroeze確定... :) – Ian

1

您設置localDate新的默認值

this.localDate = new DateTime();