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
How do I get the system date and time and store in a variable
提问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
回答by BlackBear
Here it is:
这里是:
var time = DateTime.Now;
回答by BlackBear
DateTime currentTime = DateTime.Now;