在C#中将日期时间转换为特定格式

我想转换日期时间来指定格式

Wed Aug 01 2012 14:37:50 GMT+0530 (India Standard Time) 

其实我想在网页上使用Jquery显示Timer。 所以我尝试了一些我知道的格式。 从http://www.dotnetperls.com/datetime-format找到了一些但是没有一个返回我需要的结果。 实际上我必须从服务器传递时间所以我尝试了以下代码。 代码背后

 protected void Button3_Click(object sender, EventArgs e) { //string hello = DateTime.UtcNow.ToString(); string hello = String.Format("{0:F}", DateTime.UtcNow); DateTime.UtcNow.ToString(""); ScriptManager.RegisterStartupScript(this, this.GetType(), "hdrEmpty1", "show(" + hello + ")", true); } 

jQuery的

 function show(datetime) { alert(datetime); var Digital = datetime //new Date() var hours = Digital.getHours() var minutes = Digital.getMinutes() var seconds = Digital.getSeconds() var dn = "AM" if (hours > 12) { dn = "PM" hours = hours - 12 } if (hours == 0) hours = 12 if (minutes <= 9) minutes = "0" + minutes if (seconds <= 9) seconds = "0" + seconds document.getElementById('').innerHTML = hours + ":" + minutes + ":" + seconds + " " + dn setTimeout("show()", 1000) } 

您可以使用date.ToString("format")来执行此操作。 Microsoft提供了有关如何根据需要格式化日期的完整参考 。

编辑:

也许没有准备好的格式与您的格式完全匹配,但您可以根据上述参考中提供的格式说明符组合您自己的格式。

 // This will output something like Wed Aug 01 2012 date.ToString("ddd MMM dd yyyy"); 

我相信你可以按照相同的模式自己完成剩下的工作。

您可以使用String.Format()并指定自己的自定义格式 – ddd mmm dd yyyy 。 亲自尝试探索更多。

没有理由提供已经提供的信息,你不能自己解决这个问题,但是要获得字符串读数:

 "Wed Aug 01 2012 14:37:50 GMT+0530 (India Standard Time)" 

那么你想要的是以正确的forms(“2012年8月1日星期三14:37:50”位)获得日期和时间,最后添加“GMT + 0530(印度标准时间)”。 假设那个位当然是一样的。

所以你需要的代码是:

 string string_name = (date.ToString("ddd MMM dd yyyy HH:mm:ss") + "GMT+0530 \(India Standard Time\)"); //string_name will be in the form "Wed Aug 01 2012 14:37:50 GMT+0530 (India Standard Time)" 

但是,正如我所说,这是你应该能够使用提供的参考资料自己解决的问题。

如果您不想硬编码GMT偏移并且不能依赖当地时间为印度标准时间,您可以从TimeZoneInfo提取此信息:

 // get UTC from local time var today = DateTime.Now.ToUniversalTime(); // get IST from UTC var ist = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(today, "UTC", "India Standard Time"); // find the IST TimeZone var tzi = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time"); // get the UTC offset TimeSpan var offset = tzi.GetUtcOffset(today); // determine the TimeSpan sign var sign = offset.Ticks < 0 ? "-" : "+"; // use a custom format string var formatted = string.Format(CultureInfo.InvariantCulture, "{0:ddd MMM HH:mm:ss} GMT{1}{2:hhmm}", today, sign, offset); 

试试这个在c#中将datetime转换为印度日期格式

 IFormatProvider culture = new System.Globalization.CultureInfo("hi-IN", true); DateTime dt2 = DateTime.Parse(txtStatus.Text, culture, System.Globalization.DateTimeStyles.AssumeLocal);