簡體   English   中英

使用VB.NET格式化日期

[英]Using VB.NET to format a date

剛剛開始從VB6升級到VB.Net。

txtFrom.Text = "1/8"
txtFrom.Text = Format(txtFrom.Text, "dd/MM/yyyy")

此代碼在文本框中生成DD/MM/YYYY

我應該怎么做才能生產01/08/13

解析日期。 重新格式化日期。

Dim d As Date = Date.ParseExact(txtFrom.Text, "d/M", CultureInfo.InvariantCulture)
txtFrom.Text = d.ToString("dd/MM/yy")

自訂日期格式字符串

我應該怎么做才能生產01/08/13?

dd/MM/yy

帶有"dd/MM/yyyy"的格式函數將格式化日期對象,而不是字符串。 您可以使用CDate將字符串從文本框轉換為日期:

txtFrom.Text = Format(CDate(txtFrom.Text), "dd/MM/yyyy")

如果txtFrom.Text是無效日期,您可能需要使用IsDate或Try-Catch塊。

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")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM