[英]ASP.net - C# Set input type: datetime-local to current date
This is how I declared the text field on my aspx file:这就是我在 aspx 文件中声明文本字段的方式:
<input type="datetime-local" class="form-control" id="inputDate" runat="server">
and on my aspx.cs file's page load:在我的 aspx.cs 文件的页面加载上:
inputDate.Value = DateTime.Now.ToString("MM/dd/yyyy hh:mm tt");
My goal is that when the page loads, inputDate field contains the current date with this "MM/dd/yyyy hh:mm tt" format我的目标是,当页面加载时, inputDate 字段包含具有“MM/dd/yyyy hh:mm tt”格式的当前日期
but it doesn't work.但它不起作用。 Nothing's happening.
什么都没有发生。
The input datetime-local
requires letter T in uppercase for date-time.输入
datetime-local
需要大写字母 T 表示日期时间。 Read here: https://www.w3.org/TR/html-markup/input.datetime-local.html在这里阅读: https : //www.w3.org/TR/html-markup/input.datetime-local.html
Example: 2016-03-23T05:47:48示例:2016-03-23T05:47:48
so you could do something like this:所以你可以做这样的事情:
var localDateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss").Replace(' ','T');
inputDate.Value = localDateTime;
html5 input datetime-local html5 输入日期时间-本地
var localDateTime = DateTime.Now.ToString("s");
inputDate.Value = localDateTime;
If you are having trouble with date format, you can use the overloaded version of DateTime.ToString() , mentioned below.如果您在日期格式方面遇到问题,您可以使用下面提到的DateTime.ToString()的重载版本。
DateTime.Now.ToString("MM/dd/yyyy hh:mm tt",
System.Globalization.CultureInfo.InvariantCulture);
It'll enforce your specified format irrespective of what culture setting your server machine has.无论您的服务器机器具有什么文化设置,它都会强制执行您指定的格式。
In a classic ASP.NET WebForm you can try the following:在经典的 ASP.NET WebForm 中,您可以尝试以下操作:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>TEST</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</div>
</form>
</body>
</html>
and in the code behind:并在后面的代码中:
protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Text = DateTime.Now.ToString("MM/dd/yyyy hh:mm tt");
}
Also, instead of TextBox
you can use ASP.NET Label
control for read-only functionality.此外,您可以使用 ASP.NET
Label
控件代替TextBox
来实现只读功能。 This will return the DateTime
value pertinent to the server time zone.这将返回与服务器时区相关的
DateTime
值。 In order to implement a Universal Time use:为了实现世界时使用:
TextBox1.Text = DateTime.Now.ToUniversalTime().ToString("MM/dd/yyyy hh:mm tt");
Then you can apply AddHours()
function to adjust for the difference in time zones.然后您可以应用
AddHours()
函数来调整时区差异。
Hope this may help.希望这可能会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.