如何在vb.net中编写日期代码?

时间:2009-08-27 04:58:36

标签: vb.net

VB代码。

dteFrom = Format(CDate(Year(Date) & "-" & Month(Date) & "-" & "01"), "yyyy-mm-dd")
dteTo = Format(CDate(Year(Date) & "-" & Month(Date) & "-" &  DaysInMonth(dteFrom)), "yyyy-mm-dd")

我在VB.NET中复制此代码,显示错误(日期)

dteFrom = Format(CDate(Year(Of Date)() & "-" & Month(Of Date)() & "-" & "01"), "yyyy-mm-dd")
dteTo = Format(CDate(Year(Of Date)() & "-" & Month(Of Date)() & "-" & DaysInMonth(dteFrom)), "yyyy-mm-dd")

任何人都可以帮助解决这个问题。

需要VB.Net代码。

3 个答案:

答案 0 :(得分:4)

看起来你想要两个字符串代表当月的第一天和最后一天。在这种情况下,您可以执行以下操作:

Dim today As Date = Date.Today
Dim desiredFormat As String = "yyyy-MM-dd"

Dim fromDate As Date = New Date(today.Year, today.Month, 1)
Dim dteFrom As String = fromDate.ToString(desiredFormat)

Dim toDate As Date = fromDate.AddDays(Date.DaysInMonth(today.Year, today.Month) - 1)
Dim dteTo As String = toDate.ToString(desiredFormat)

答案 1 :(得分:1)

这将是您最接近原始代码的地方:

dteFrom = Format(CDate(Year(Date.Today) & "-" & Month(Date.Today) & "-" & "01"), "yyyy-MM-dd")
dteTo = Format(CDate(Year(Date.Today) & "-" & Month(Date.Today) & "-" & Date.DaysInMonth(Year(Date.Today), Month(Date.Today))), "yyyy-MM-dd")

这将是一种更“.NET”的方式:

dteFrom = String.Format("{0:yyyy-MM}-01", Date.Today)
dteTo = String.Format("{0:yyyy-MM}-{1:00}", Date.Today, Date.DaysInMonth(Year(Date.Today), Month(Date.Today)) )

答案 2 :(得分:0)

类似的东西:

Dim dateString as String = string.format("{0:yyyy-MM-dd}", New DateTime(DateTime.Now.Year,DateTime.Now.Month, 1))