在编程中我们经常要按固定格式取系统时间,比如yyyy-MM-dd,而用户可能修改了系统显示日期的格式,如yy-M-d,如果用DateTime.Now.ToString();可能就取不到想要的格式,要解决这个问题我用下面代码:
//获得系统时间
public string GetDateTime()
{
string strYear = DateTime.Now.ToString("yyyy");
string strMonth = DateTime.Now.ToString("MM");
string strDay = DateTime.Now.ToString("dd");
string strDataNow;
strDataNow = strYear + "-" + strMonth + "-" + strDay ;

return strDataNow ;
}注意:在string strMonth = DateTime.Now.ToString("MM") ;中MM必须大写,否则有可能出现 2005-38-12这种错误日期。
//获得系统时间
public string GetDateTime()
{
string strYear = DateTime.Now.ToString("yyyy");
string strMonth = DateTime.Now.ToString("MM");
string strDay = DateTime.Now.ToString("dd");
string strDataNow;
strDataNow = strYear + "-" + strMonth + "-" + strDay ;
return strDataNow ;
}

浙公网安备 33010602011771号