使用 VB.NET 格式化日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19081990/
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
Using VB.NET to format a date
提问by user2829015
Just started upgrading to VB.Net from VB6.
刚开始从 VB6 升级到 VB.Net。
txtFrom.Text = "1/8"
txtFrom.Text = Format(txtFrom.Text, "dd/MM/yyyy")
This code produces DD/MM/YYYYin the text box.
此代码DD/MM/YYYY在文本框中生成。
What should I do to produce 01/08/13?
我应该怎么做才能生产01/08/13?
回答by Ry-
Parse the date. Reformat the date.
解析日期。重新格式化日期。
Dim d As Date = Date.ParseExact(txtFrom.Text, "d/M", CultureInfo.InvariantCulture)
txtFrom.Text = d.ToString("dd/MM/yy")
回答by xpda
The format function with "dd/MM/yyyy"will format a date object, not a string. You can convert the string from the textbox to a date using CDate:
格式化函数 with"dd/MM/yyyy"将格式化日期对象,而不是字符串。您可以使用 CDate 将文本框中的字符串转换为日期:
txtFrom.Text = Format(CDate(txtFrom.Text), "dd/MM/yyyy")
You might want to use IsDateor a Try-Catch block in case txtFrom.Textis an invalid date.
如果日期无效,您可能想要使用IsDate或 Try-Catch 块txtFrom.Text。
回答by Darin Dimitrov
What should I do to produce 01/08/13?
我应该怎么做才能生产 01/08/13?
dd/MM/yy
回答by Phuong Nghiem Minh
Dim sFormat As System.Globalization.DateTimeFormatInfo = New System.Globalization.DateTimeFormatInfo()
sFormat.ShortDatePattern = "dd/MM/yyyy"
txtFrom.Text = Format(Convert.ToDateTime(txtFrom.Text+Now.Year.ToString(), sFormat), "dd/MM/yyyy")

