如何获得当前时间(而不是日期和时间)?
例如:下午5:42:12
如何获得当前时间(而不是日期和时间)?
例如:下午5:42:12
当前回答
我也在尝试这个方法,发现这些页面也很有帮助。 首先是主类… https://msdn.microsoft.com/en-us/library/system.datetime (v = vs.110) . aspx
现在ToString方法的一些说明符格式… https://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo (v = vs.110) . aspx
例子:
using System;
namespace JD
{
class Program
{
public static DateTime get_UTCNow()
{
DateTime UTCNow = DateTime.UtcNow;
int year = UTCNow.Year;
int month = UTCNow.Month;
int day = UTCNow.Day;
int hour = UTCNow.Hour;
int min = UTCNow.Minute;
int sec = UTCNow.Second;
DateTime datetime = new DateTime(year, month, day, hour, min, sec);
return datetime;
}
static void Main(string[] args)
{
DateTime datetime = get_UTCNow();
string time_UTC = datetime.TimeOfDay.ToString();
Console.WriteLine(time_UTC);
Console.ReadLine();
}
}
}
我添加了TimeOfDay方法来显示你得到的默认时间是24小时也就是从午夜开始的时间
你可以使用我的getter方法();: - d
其他回答
我也在尝试这个方法,发现这些页面也很有帮助。 首先是主类… https://msdn.microsoft.com/en-us/library/system.datetime (v = vs.110) . aspx
现在ToString方法的一些说明符格式… https://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo (v = vs.110) . aspx
例子:
using System;
namespace JD
{
class Program
{
public static DateTime get_UTCNow()
{
DateTime UTCNow = DateTime.UtcNow;
int year = UTCNow.Year;
int month = UTCNow.Month;
int day = UTCNow.Day;
int hour = UTCNow.Hour;
int min = UTCNow.Minute;
int sec = UTCNow.Second;
DateTime datetime = new DateTime(year, month, day, hour, min, sec);
return datetime;
}
static void Main(string[] args)
{
DateTime datetime = get_UTCNow();
string time_UTC = datetime.TimeOfDay.ToString();
Console.WriteLine(time_UTC);
Console.ReadLine();
}
}
}
我添加了TimeOfDay方法来显示你得到的默认时间是24小时也就是从午夜开始的时间
你可以使用我的getter方法();: - d
计算当前的datetime:
DateTime theDate = DateTime.UtcNow;
string custom = theDate.ToString("d");
MessageBox.Show(custom);
获取当前日期和时间,然后只使用它的时间部分。看看MSDN文档中格式化日期时间字符串的可能性。
非常简单的datetime,现在。ToString(“hh: mm: ss tt”)
试试这个:
DateTime.Now.ToString("HH:mm:ss tt");
对于其他格式,您可以检查这个网站:c# DateTime格式