C# 如何获取系统日期和时间并存储在变量中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18704786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:57:38  来源:igfitidea点击:

How do I get the system date and time and store in a variable

c#date

提问by Al Woods

I want to store the current date and time in a variable using C#. How would I do that if it has to be in the format YYYY, MM, DD, HH, MM, SS? I.e. I know I can store midnight on January 1st, 2013 as;

我想使用 C# 将当前日期和时间存储在一个变量中。如果必须采用 YYYY、MM、DD、HH、MM、SS 格式,我该怎么做?即我知道我可以将 2013 年 1 月 1 日午夜存储为;

var time= new DateTime(2013, 1, 1, 0, 0, 0);

How do I do this with the system date and time?

如何使用系统日期和时间执行此操作?

采纳答案by Nick Raverty

var time = DateTime.Now;

Format the time when you retrieve it, not when you store it - i.e. -

在检索时格式化时间,而不是在存储时格式化 - 即 -

string formattedTime = time.ToString("yyyy, MM, dd, hh, mm, ss");

回答by It'sNotALie.

You need DateTime's static field Now:

你需要DateTime的静态字段Now

var time = DateTime.Now;

回答by Rahul Tripathi

You can try using the DateTime.Nowlike this:-

您可以尝试使用DateTime.Now像这样:-

var time = DateTime.Now;

回答by BlackBear

Here it is:

这里是:

var time = DateTime.Now;

回答by BlackBear

DateTime currentTime = DateTime.Now;