简体   繁体   English

将日期和时间加入到 VB.NET 中的 DateTime

[英]Join Date and Time to DateTime in VB.NET

I am retrieving data from DB where there is a separate date and time fields.我正在从数据库中检索数据,其中有单独的日期和时间字段。 I want to join them into a DateTime field in my VB.NET project.我想将它们加入到我的 VB.NET 项目中的 DateTime 字段中。 How would you suggest accomplishing this?你会建议如何实现这一点?

I tried this but it's not working for me.我试过这个,但它对我不起作用。 "String was not recognized as a valid DateTime." “字符串未被识别为有效的日期时间。”

Dim InDate As New DateTime(incident.IncidentDate.Value.Year, incident.IncidentDate.Value.Month, incident.IncidentDate.Value.Day, 0, 0, 0)
                    Dim InTime As New DateTime(1900, 1, 1, incident.IncidentTime.Value.Hour, incident.IncidentTime.Value.Minute, incident.IncidentTime.Value.Second)


                    Dim combinedDateTime As DateTime = DateTime.Parse((InDate.ToString("dd/MM/yyyy") + " " + InTime.ToString("hh:mm tt")))

                    rdtpIncidentDateTime.SelectedDate = combinedDateTime

You can just create a new DateTime value from the components in InDate and InTime :你可以创建一个新的DateTime从组件价值InDateInTime

Dim combinedDateTime As DateTime = New DateTime( _
  InDate.Year, InDate.Month, InDate.Day, _
  InTime.Hour, InTime.Minute, InTime.Second _
)

DateTime exposes a method called DateTime.TimeOfDay DateTime 公开了一个名为DateTime.TimeOfDay的方法

You can simply use DateTime.Add to append the time to the date.您可以简单地使用DateTime.Add将时间附加到日期。

Dim dateAndTime As DateTime = myDate.Add(myTime.TimeOfDay)
Dim CombinedDate As Date = Date1.Date + Time1.TimeOfDay

This will work when you want to combine the DATE from one variable and the TIME from a different variable.当您想要组合来自一个变量的 DATE 和来自不同变量的 TIME 时,这将起作用。

Date is an alias to DateTime.日期是日期时间的别名。 In VB.NET, they are the same thing.在 VB.NET 中,它们是一回事。 You can see all the aliases in this chart on MSDN.您可以在 MSDN 上查看此图表中的所有别名。 Link 关联

您可以在一行中完成...声明您的日期并使用时间的事件值而不是零。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM