繁体   English   中英

Datetime.utc在事件查看器中返回1-1-0001 00:00:00

[英]Datetime.utc returns 1-1-0001 00:00:00 in event viewer

我想将当前日期返回给事件记录器,我已经尝试过了:

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。 而不是实际时间。

您再次将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;

    }
}

您将localDate设置为新的默认值

this.localDate = new DateTime();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM