How to calculate time in VB.NET

motokent
motokent used Ask the Experts™
on
This might be a very simple question for some, but I'm very frustrated with it and need some help.

I need to calculate the datetime for (now - 12 hours) in 24-hr format
Then I need to extract the components that I can use as strings.

dim mo as string =???
dim da as string =???
dim yr as string =???
dim hr as string =???
dim mi as string =???
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Commented:
You can use the Date.AddHours method to subtract 12 from the current datetime.  Soemthing like so...
Dim past As Date = DateTime.Now.AddHours(-12)
Dim mo As String = past.Month
Dim da As String = past.Day
...etc

Open in new window

Author

Commented:
Thanks for the quick and good reply.
Top Expert 2005

Commented:
Dim dt As Date = DateTime.Now.AddHours(-12)

            ''24 hour format
            Debug.Print(dt.ToString("MM/dd/yyyy HH:mm:ss"))

            Dim mo As String = dt.Month.ToString
            Dim da As String = dt.Day.ToString
            Dim yr As String = dt.Year.ToString
            Dim hr As String = dt.Hour.ToString
            Dim mi As String = dt.Minute.ToString

Date formats:
http://riderdesign.com/articles/Formatting-dates-with-VB.NET-and-ASP.NET.aspx
Hi, hope this helps:
    Sub Main()

        Dim TimeNow As DateTime = Now()
        Dim NowMinus24 As DateTime = TimeNow.AddHours(-12)

        Dim mo As String = NowMinus24.Month
        Dim da As String = NowMinus24.Day
        Dim yr As String = NowMinus24.Year
        Dim hr As String = NowMinus24.Hour
        Dim mi As String = NowMinus24.Minute

        Dim monthname As String = NowMinus24.ToString("MMMM")
        Dim dayofweek As String = NowMinus24.DayOfWeek.ToString
    End Sub

Open in new window


dim startTime as DateTime = DateTime.Now

Dim endTime as DateTime =DateTime.Now.Addhours(-12 )
    
Dim span as TimeSpan = endTime.Subtract ( startTime )

Then you can assign it to a text box: i.e

Textbox1.text=span.hours

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial