How do I subtract a month from a date object in VB.NET?
I have tried:
Today.AddMonths(-1)
However, given that Today is 01-Jan-2010, the result I get is 01-Dec-2010. The answer I want is 01-Dec-2009.
Is there a convenient way of doing this within the .NET framework?
You actually have to transport Today into a variable and let that assignment work there. The following code will produce the result you expect (I just verified it because your post made me think twice).
Dim dt As DateTime = Date.Today
dt = dt.AddMonths(-2)
Dim x As String = dt.ToString()
This works fine, you need to remember that the DateTime is imutable.
Dim d As DateTime
d = New DateTime(2010, 1, 1)
d = d.AddMonths(-1)
Have a look at DateTime Structure
A calculation on an instance of
DateTime, such as Add or Subtract,
does not modify the value of the
instance. Instead, the calculation
returns a new instance of DateTime
whose value is the result of the
calculation.
Dim d As DateTime = #1/1/2010#
d = d.AddMonths(-1)
I have used the following and it works.
Dim dtToday As DateTime = Date.Today
dtToday = dtToday.AddMonths(-2)
Related
I need help with a quick question I a string "07/10/2014" how can I get first the year "2014",second the month "10" ,third the day- "07" with out "/" only the values in VB.NET
Please show me the full way how to do it.
First declare it like this Dim x as Date = "07/10/2014". And to get the individual values use x.Day, x.Month and x.Year
Use the DateTime.Parse() method then use the return DateTime structure to extract the Month, Day, Year properties (similar to DJK's answer above).
If the thread's current culture is set to one that understands "mm/dd/yyyy" format, then the code can be as simple as:
Dim dt As DateTime = DateTime.Parse("07/15/2014")
MessageBox.Show(String.Format("Month: {0}; Day: {1}; Year: {2}", dt.Month, dt.Day, dt.Year))
Have a look at this.
Dim MyDate As Date
MyDate = "07/10/2014"
MsgBox(Format(MyDate, "dd")) ' dd gives you day number
MsgBox(Format(MyDate, "MM")) ' MM gives you month number
MsgBox(Format(MyDate, "YYYY")) ' YYYY gives you year number
The full list of date fomatting string could be found here (MSDN)
UPDATE
Use following example to assign to a string variable
Dim DayOfString As String DayOfString
DayOfString = Format(MyDate, "dd")
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.
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:
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
You can simply use DateTime.Add to append the time to the date.
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 is an alias to DateTime. In VB.NET, they are the same thing. You can see all the aliases in this chart on MSDN. Link
You can do it in one line...declare your indate and use the incident values for the time instead of zeros.
I have 2 fields fromDate and toDate for a school's term. Say their values are '01-06-2013' to '01-09-2013'. How do I get the total number of days in the term, in vb.net?
You can try this in vb.net:
Dim t1 As DateTime = Convert.ToDateTime("01-06-2013")
Dim t2 As DateTime = Convert.ToDateTime("01-09-2013")
MessageBox.Show(t2.Subtract(t1).Days)
I think сlass DateDiff can help you: http://msdn.microsoft.com/ru-ru/library/ms189794.aspx
Try this (C#):
TimeSpan timespan = Convert.ToDateTime("01-09-2013").Subtract(Convert.ToDateTime("01-06-2013"));
Response.Write(timespan.Days+1);
Usually the Subtract method return a value that is one less than the correct value so added one to get excat no of days
OR:
DateDiff(DateInterval.Day , curDate, srDate) //can replace the first argument with "d"
Also check this link
I have 2 columns, one for start-time and the other for the end-time. They both are of the type nvarchar so that i can compare them.
I have a text box that will receive time from the user and will post-back automatically to check if the the time is valid or not.
Dim compared_time_1 As DateTime
Dim compared_time_2 As DateTime
Dim select_time As SqlCommand
select_time = New SqlCommand("select Start_Time , End_Time from Clinic_Schedule where Schedule_no = #sch_no", appt_DB_1)
select_time.Parameters.AddWithValue("#sch_no", Sch_no)
Dim time_rdr As SqlDataReader
time_rdr = select_time.ExecuteReader()
While time_rdr.Read
compared_time_1 = DateTime.Parse(start_time_1)
compared_time_2 = DateTime.Parse(end_time_1)
start_time_1 = time_rdr(0).ToString
end_time_1 = time_rdr(1).ToString
If appt_time_txt0.Text >= start_time_1 And appt_time_txt0.Text <= end_time_1 Then
date_valid_lbl0.Visible = True
date_valid_lbl0.Text = "*Valid Time"
Else
time_valid_lbl0.Visible = True
time_valid_lbl0.Text = "*Not Valid Time"
End If
End While
time_rdr.Close()
I don't know if i have a problem with my logic XD.
the data filled in thoses columns are in this format : 00:00AM or 00:00PM.
I will appreciate your help .. thanks
Seems like you are comparing a string against a date datatype.
Ensure that you are converting both into date datatype as follows.
Note the space between the seconds and 'AM'.
time1=CDate("3:19:40 AM")
time2=CDate("3:10:40 AM")
Then perform comparisms as follows:
if time1>time2 then
'logic
end if
It looks like you're doing the parse before loading the data from your reader.
compared_time_1 = DateTime.Parse(start_time_1)
compared_time_2 = DateTime.Parse(end_time_1)
start_time_1 = time_rdr(0).ToString
end_time_1 = time_rdr(1).ToString
should be
start_time_1 = time_rdr(0).ToString
end_time_1 = time_rdr(1).ToString
compared_time_1 = DateTime.Parse(start_time_1)
compared_time_2 = DateTime.Parse(end_time_1)
But I would even do it differently than that. If you're trying to tell if the times are valid, you can use the datetime TryParse method. Perhaps a bit of refactoring might also help you. Finally, just be aware that comparing times might be problematic if there is ever a chance that schedule item might begin before midnight and end after midnight the next day.
Sub ReadingData()
'initializing reader stuff here...
Dim dtStart As DateTime, dtEnd As DateTime
If DateTime.TryParse(time_rdr(0).ToString, dtStart) = False Then
HandleInvalidTime()
End If
If DateTime.TryParse(time_rdr(1).ToString, dtEnd) = False Then
HandleInvalidTime()
End If
'Closing out reader stuff here...
HandleValidTime(dtStart, dtEnd)
End Sub
Sub HandleValidTime(TheStartTime As DateTime, TheEndTime As DateTime)
'Do Stuff
End Sub
Sub HandleInvalidTime()
'Do Stuff
End Sub
I'm writing in ASP.NET 4 / VB.NET. I am querying an MSSQL database and sometimes have records come back with no results...so I enclosed the call I was making upon the results in an If..Else clause to set a default value if the database comes back with no results...but now I am getting this "Object variable or With block variable not set error". Here is the relevant code:
Dim clcfirst
Dim rhcfirst
Dim clcdate As Date
Dim rhcdate As Date
If IsNothing(clcexists) Then
clcfirst = Date.Now.Subtract(year)
rhcfirst = Date.Now.Subtract(year)
clcdate = clcfirst
rhcdate = rhcfirst
Else
clcfirst = clcexists.FirstOrDefault()
rhcfirst = rhcexists.FirstOrDefault()
clcdate = clcfirst.SignatureDate
rhcdate = rhcfirst.SignatureDate
End If
Where is the DateTime year variable being set? Could that be null?
If you want to subtract a year, you could just do:
clcdate = Date.Now.AddYears(-1)
rhcdate = Date.Now.AddYears(-1)