Results 1 to 25 of 25

Thread: [RESOLVED] How to calculate with date AND time in VB?

  1. #1

    Thread Starter
    Junior Member
    Join Date
    Oct 2010
    Location
    Zagreb
    Posts
    29

    Resolved [RESOLVED] How to calculate with date AND time in VB?

    Hi,

    I'm new with VB 6.0 and could really use some help.

    I have to get time difference (time interval) from entered time AND date in the text box and current time AND date.

    Also, how to define that data entered in text box is time and date in the code ?



    Please help me.

    Morris

  2. #2
    Next Of Kin baja_yu's Avatar
    Join Date
    Aug 2002
    Location
    /dev/root
    Posts
    5,989

    Re: How to calculate with date AND time in VB?

    DateDiff function can handle that.

  3. #3
    Discovering Life Siddharth Rout's Avatar
    Join Date
    Feb 2005
    Location
    Mumbai, India
    Posts
    12,001

    Re: How to calculate with date AND time in VB?

    Also, how to define that data entered in text box is time and date in the code ?
    Welcome to the forums Morris_Zg

    Use the Microsoft Masked Edit Control so that you don't have to write validation code
    A good exercise for the Heart is to bend down and help another up...
    Please Mark your Thread "Resolved", if the query is solved


    MyGear:
    ★ CPU ★ Ryzen 5 5800X
    ★ GPU ★ NVIDIA GeForce RTX 3080 TI Founder Edition
    ★ RAM ★ G. Skill Trident Z RGB 32GB 3600MHz
    ★ MB ★ ASUS TUF GAMING X570 (WI-FI) ATX Gaming
    ★ Storage ★ SSD SB-ROCKET-1TB + SEAGATE 2TB Barracuda IHD
    ★ Cooling ★ NOCTUA NH-D15 CHROMAX BLACK 140mm + 10 of Noctua NF-F12 PWM
    ★ PSU ★ ANTEC HCG-1000-EXTREME 1000 Watt 80 Plus Gold Fully Modular PSU
    ★ Case ★ LIAN LI PC-O11 DYNAMIC XL ROG (BLACK) (G99.O11DXL-X)
    ★ Monitor ★ LG Ultragear 27" 240Hz Gaming Monitor
    ★ Keyboard ★ TVS Electronics Gold Keyboard
    ★ Mouse ★ Logitech G502 Hero

  4. #4
    PowerPoster Ellis Dee's Avatar
    Join Date
    Mar 2007
    Location
    New England
    Posts
    3,530

    Re: How to calculate with date AND time in VB?

    Use the IsDate() function to determine if a string (textbox.text) is a valid datetime.

    In VB6, dates and times are stored in the same variable, called datetime. There is no separate date or time data types. Internally a datetime variable is a double precision decimal, where the whole number is the date and the decimal part is the time.

    To make dealing with datetimes more intuitive, VB6 has the following datetime functions:

    Date() - return the current date with no time value (midnight)
    Now() - return the current date and time
    DateAdd() - to add (or subtract if negative) any amount of time
    DateDiff() - how many (seconds/hours/days/etc...) between two moments in time?
    Day() Month() Year() Hour() Minute() Second() - Get just that piece of the datetime
    DateSerial() - Construct a date manually, can be used to add/subtract intervals of time
    TimeSerial() - Construct a time manually, can be used to add/subtract intervals of time

    The Serial() functions are super-useful. To create a datetime from them, simply add them together. eg: Datetime = DateSerial(<whatever>) + TimeSerial(<whatever>). Many of the arguments you send to the Serial() functions are usually the "piece" functions. As a quick example, this returns the first day of the current month:

    DateSerial(Year(Date), Month(Date), 1)

    If you specify "invalid" values, the serial functions simply roll over. So to get the day before the first day of this month:

    DateSerial(Year(Date), Month(Date), 0)

    You can also toss in expressions like adding or subtracting. Like, say, the first day of next month:

    DateSerial(Year(Date), Month(Date) + 1, 1)

    Combining techniques, the day before the first day of next month:

    DateSerial(Year(Date), Month(Date) + 1, 0)

    The "day before the first day of next month" is another way of saying "the last day of this month." This would be a fairly complex thing to calculate manually, what with the whole "30 days has September..." deal, not to mention leap years.

    DateAdd() and DateDiff() are quite helpful, but as this example shows, the Serial() functions are where the real power is.
    Last edited by Ellis Dee; Oct 20th, 2010 at 11:54 AM.

  5. #5
    PowerPoster Ellis Dee's Avatar
    Join Date
    Mar 2007
    Location
    New England
    Posts
    3,530

    Re: How to calculate with date AND time in VB?

    Quote Originally Posted by Morris_Zg View Post
    I have to get time difference (time interval) from entered time AND date in the text box and current time AND date.

    Also, how to define that data entered in text box is time and date in the code ?
    Specifically:
    vb Code:
    1. If IsDate(Text1.Text) Then
    2.     Seconds = DateDiff("s", Text1.Text, Now())
    3. End If
    Note that DateDiff() returns a positive number if the first datetime is earlier than the second one. If you always want a positive number, you could use the Abs() function to return the absolute value.

    I always get intervals in seconds, because then I have complete control to handle the exact difference how I want. Divide the total seconds by 3600 and you have the number of hours, for example.

  6. #6

    Thread Starter
    Junior Member
    Join Date
    Oct 2010
    Location
    Zagreb
    Posts
    29

    Re: How to calculate with date AND time in VB?

    Thanks! Datediff is exactly what I need.

    I need it to set up sleep function. So would it be wright if I put:

    Code:
    If IsDate(Text1.Text) Then
    MiliSeconds = DateDiff("ms", Now(), Text1.Text)
    Sleep MiliSeconds       
    End If
    ?

    Does something go within Now(??) ?

  7. #7
    Next Of Kin baja_yu's Avatar
    Join Date
    Aug 2002
    Location
    /dev/root
    Posts
    5,989

    Re: How to calculate with date AND time in VB?

    Now by itself will work, it returns current date and time. Though I'm not sure that DateDiff has that precise a resolution to resolve into miliseconds. Seconds might be the smallest it can go.

  8. #8

    Thread Starter
    Junior Member
    Join Date
    Oct 2010
    Location
    Zagreb
    Posts
    29

    Re: How to calculate with date AND time in VB?

    Then

    Code:
    If IsDate(Text1.Text) Then
    MiliSeconds = (DateDiff("s", Now(), Text1.Text))*1000
    Sleep MiliSeconds       
    End If
    ?

  9. #9
    Next Of Kin baja_yu's Avatar
    Join Date
    Aug 2002
    Location
    /dev/root
    Posts
    5,989

    Re: How to calculate with date AND time in VB?

    That would be correct.

  10. #10

    Thread Starter
    Junior Member
    Join Date
    Oct 2010
    Location
    Zagreb
    Posts
    29

    Re: How to calculate with date AND time in VB?

    thanks

  11. #11
    Next Of Kin baja_yu's Avatar
    Join Date
    Aug 2002
    Location
    /dev/root
    Posts
    5,989

    Re: How to calculate with date AND time in VB?

    You're welcome.

    Just a note, Sleep function will 'freeze' your application for the duration of the set interval. No processing will be done in the mean time so if the interval is big it will appear as if it was 'not responding'.

  12. #12

    Thread Starter
    Junior Member
    Join Date
    Oct 2010
    Location
    Zagreb
    Posts
    29

    Re: How to calculate with date AND time in VB?

    Can this pausing be interrupeted? For example, if the user wants to stop the sleep because he changes mind or wants to exit the application, or change date and time?

  13. #13
    Freelancer akhileshbc's Avatar
    Join Date
    Jun 2008
    Location
    Trivandrum, Kerala, India
    Posts
    7,652

    Re: How to calculate with date AND time in VB?

    Quote Originally Posted by Morris_Zg View Post
    Can this pausing be interrupeted? For example, if the user wants to stop the sleep because he changes mind or wants to exit the application, or change date and time?
    I think, for this purpose a loop or something will be better.

    An example:
    vb Code:
    1. Option Explicit
    2.  
    3. Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
    4.  
    5. Dim bolExit          As Boolean
    6. Dim lngTotalmSec     As Long
    7. Dim lngCurrentmSec   As Long
    8.  
    9. Private Sub Command1_Click()
    10.     lngTotalmSec = 1000     '~~~ Total time to sleep
    11.     lngCurrentmSec = 0      '~~~ Holds how much time slept
    12.    
    13.     Do While (lngCurrentmSec < lngTotalmSec)    '~~~ Loop until the total time is reached
    14.         If bolExit = True Then  '~~~ Check if the user wants to exit the sleeping process
    15.             bolExit = False
    16.             MsgBox "Hey...!!!"
    17.             Exit Do
    18.         Else                    '~~~ Otherwise, sleep for a few millisecs
    19.             lngCurrentmSec = lngCurrentmSec + 10
    20.             Sleep 10
    21.             DoEvents    '~~~ This will prevent the "Not Responding" message
    22.         End If
    23.     Loop
    24.    
    25.     MsgBox "Huuahh!! I had a great sleep "
    26. End Sub
    27.  
    28. '~~~ If user wants to exit the sleep
    29. Private Sub Command2_Click()
    30.     bolExit = True
    31. End Sub

    If my post was helpful to you, then express your gratitude using Rate this Post.
    And if your problem is SOLVED, then please Mark the Thread as RESOLVED (see it in action - video)
    My system: AMD FX 6100, Gigabyte Motherboard, 8 GB Crossair Vengance, Cooler Master 450W Thunder PSU, 1.4 TB HDD, 18.5" TFT(Wide), Antec V1 Cabinet

    Social Group: VBForums - Developers from India


    Skills: PHP, MySQL, jQuery, VB.Net, Photoshop, CodeIgniter, Bootstrap,...

  14. #14
    PowerPoster Ellis Dee's Avatar
    Join Date
    Mar 2007
    Location
    New England
    Posts
    3,530

    Re: How to calculate with date AND time in VB?

    I think it's cleaner to use a timer. Set its enabled to False and interval to something between 400 and 1000.
    vb Code:
    1. Option Explicit
    2.  
    3. Private mdtmWake As Date
    4.  
    5. Private Sub Command1_Click()
    6.     ' Sleep for 10 seconds
    7.     mdtmWake = DateAdd("s", 10, Now())
    8.     Timer1.Enabled = True
    9. End Sub
    10.  
    11. Private Sub Timer1_Timer()
    12.     If mdtmWake > Now() Then Exit Sub
    13.     Timer1.Enabled = False
    14.     ' Do the "wake up" code here
    15.     MsgBox "I'm awake!"
    16. End Sub

  15. #15

    Thread Starter
    Junior Member
    Join Date
    Oct 2010
    Location
    Zagreb
    Posts
    29

    Re: How to calculate with date AND time in VB?

    Hi!

    Akhileshbc, I tried your code and this is what I wanted. Thanks.

    Ellis Dee, I didn't actually understand what exactly does your code do. Can it be used to do some actions every specific interval of time (this interval would user enter in textbox) and loop these actions every entered interval of time until the End Time and Date (that would be entered in another text box)?

  16. #16
    PowerPoster Ellis Dee's Avatar
    Join Date
    Mar 2007
    Location
    New England
    Posts
    3,530

    Re: How to calculate with date AND time in VB?

    Something like this would do it:
    vb Code:
    1. Option Explicit
    2.  
    3. Private mdtmStart As Date
    4. Private mdtmEnd As Date
    5. Private mlngInterval As Long
    6.  
    7. Private Sub Command1_Click()
    8.     ' Validate
    9.     If Val(txtInterval.Text) <= 0 Then
    10.         MsgBox "Interval must be greater than zero", vbInformation, "Notice"
    11.         txtInterval.SetFocus
    12.         Exit Sub
    13.     End If
    14.     If Not IsDate(txtEnd.Text) Then
    15.         MsgBox "Invalid end time", vbInformation, "Notice"
    16.         txtEnd.SetFocus
    17.         Exit Sub
    18.     End If
    19.     ' Begin loop
    20.     mdtmStart = Now()
    21.     mdtmEnd = CDate(txtEnd.Text)
    22.     mlngInterval = Val(txtInterval.Text) ' Interval in seconds
    23.     Timer1.Interval = 500
    24.     Timer1.Enabled = True
    25. End Sub
    26.  
    27. Private Sub Timer1_Timer()
    28.     If Now() >= mdtmEnd Then
    29.         Timer1.Enabled = False
    30.         MsgBox "End time reached. Loop finished.", vbInformation, "Notice"
    31.         Exit Sub
    32.     End If
    33.     If Now() - mdtmStart < mlngInterval Then Exit Sub
    34.     mdtmStart = Now()
    35.     Timer1.Enabled = False
    36.     SomeAction
    37.     Timer1.Enabled = True
    38. End Sub
    39.  
    40. Private Sub SomeAction()
    41.     ' The "some action" that gets done every specific interval of time
    42.     ' Should probably rename this function (And its call in the Timer1_Timer event)
    43. End Sub
    This isn't written to be super-precise, meaning it (like akhileshbc's solution) will add in the processing time each iteration. For example, if you want to run something every 10 seconds that takes 1 second to run, it'll run at 10 seconds, then 21 seconds, then 32, etc... Even if the actual processing time is pretty small, it won't run exactly 6 times per minute, which could confuse the users.

    This timer approach can be pretty easily modified to run every x seconds regardless of how long the processing takes.
    Last edited by Ellis Dee; Oct 23rd, 2010 at 10:42 AM.

  17. #17

    Thread Starter
    Junior Member
    Join Date
    Oct 2010
    Location
    Zagreb
    Posts
    29

    Re: How to calculate with date AND time in VB?

    Quote Originally Posted by Ellis Dee View Post
    This timer approach can be pretty easily modified to run every x seconds regardless of how long the processing takes.
    Thanks. I'll take a look at the timer. Planned actions will last for a couple of minutes, so this is significant delay then. It must run every x seconds regardless of how long the processing takes.

  18. #18
    PowerPoster Ellis Dee's Avatar
    Join Date
    Mar 2007
    Location
    New England
    Posts
    3,530

    Re: How to calculate with date AND time in VB?

    Ah. I can add the changes to run every x seconds regardless of how long processing takes in a matter of minutes, so I'll do that for you. But first, what exactly would you expect to be entered into the two texboxes? If you tell me that I can set it up correctly right out of the gate instead of you having to fiddle with it to change from seconds to a time format.

  19. #19

    Thread Starter
    Junior Member
    Join Date
    Oct 2010
    Location
    Zagreb
    Posts
    29

    Re: How to calculate with date AND time in VB?

    I would be very grateful to you if you would do that

    Take a look here:
    http://www.vbforums.com/showthread.php?t=630881

    I attached a rar of my project. The text boxes are in frmTimer. In textbox txtEnd should be entered date and time when application stops performing actions, and the interval between actions (in minutes) that should be entered in txtInterval. The first box was supposed to be for the clock showing actual time, but it's sufficient now when there will be application pausing, so I'll delete it.

  20. #20
    PowerPoster Ellis Dee's Avatar
    Join Date
    Mar 2007
    Location
    New England
    Posts
    3,530

    Re: How to calculate with date AND time in VB?

    Here's the modification to run every x minutes regardless of how long the processing takes.
    vb Code:
    1. Option Explicit
    2.  
    3. Private mdtmStart As Date
    4. Private mdtmNext As Date
    5. Private mdtmEnd As Date
    6. Private mlngInterval As Long
    7. Private mlngIteration As Long
    8.  
    9. Private Sub Command1_Click()
    10.     ' Validate
    11.     If Val(txtInterval.Text) <= 0 Then
    12.         MsgBox "Interval must be greater than zero", vbInformation, "Notice"
    13.         txtInterval.SetFocus
    14.         Exit Sub
    15.     End If
    16.     If Not IsDate(txtEnd.Text) Then
    17.         MsgBox "Invalid end time", vbInformation, "Notice"
    18.         txtEnd.SetFocus
    19.         Exit Sub
    20.     End If
    21.     ' Begin loop
    22.     mdtmStart = Now()
    23.     mdtmEnd = CDate(txtEnd.Text)
    24.     mlngInterval = Val(txtInterval.Text) * 60 ' Interval in seconds
    25.     mlngIteration = 0
    26.     mdtmNext = Now()
    27.     Timer1.Interval = 500
    28.     Timer1.Enabled = True
    29. End Sub
    30.  
    31. Private Sub Timer1_Timer()
    32.     If Now() >= mdtmEnd Then
    33.         Timer1.Enabled = False
    34.         MsgBox "End time reached. Loop finished.", vbInformation, "Notice"
    35.         Exit Sub
    36.     End If
    37.     If mdtmNext > Now() Then Exit Sub
    38.     mlngIteration = mlngIteration + 1
    39.     mdtmNext = DateAdd("s", mlngIteration * mlngInterval, mdtmStart)
    40.     Timer1.Enabled = False
    41.     SomeAction
    42.     Timer1.Enabled = True
    43. End Sub
    44.  
    45. Private Sub SomeAction()
    46.     ' The "some action" that gets done every specific interval of time
    47.     ' Should probably rename this function (And its call in the Timer1_Timer event)
    48. End Sub
    I wasn't sure if you wanted the first iteration to be immediate, or if you want to wait an initial interval. For example, if the processing is to be every 10 minutes, should it start immediately or wait 10 minutes before the first batch gets done?

    I wrote it to start immediately.
    Last edited by Ellis Dee; Oct 24th, 2010 at 12:14 PM.

  21. #21

    Thread Starter
    Junior Member
    Join Date
    Oct 2010
    Location
    Zagreb
    Posts
    29

    Re: How to calculate with date AND time in VB?

    Quote Originally Posted by Ellis Dee View Post
    I wrote it to start immediately.
    Thanks. I'll try it.
    And yes, it should start immediately because I'll put it after akhileshbc's code (Oct 22nd, 2010) that pauses the application till the Start Time. This is because start time could be set for hours from current time (when setting it), so I didn't want that application does the IF function (check if Start Time (txtStart.Text) = Now) for hours... I 've red that this loop could lead to overheating the laptop and employ CPU too much. Am I thinking right? Do You think that these two codes together are right solution?

  22. #22

    Thread Starter
    Junior Member
    Join Date
    Oct 2010
    Location
    Zagreb
    Posts
    29

    Re: How to calculate with date AND time in VB?

    I tried the code and it returns "compile error: variable not defined". It marks Timer1 in line 27.

    Why would this be?

  23. #23
    PowerPoster Ellis Dee's Avatar
    Join Date
    Mar 2007
    Location
    New England
    Posts
    3,530

    Re: How to calculate with date AND time in VB?

    Because you either don't have a timer control on the form or you didn't change all the references to "Timer1" in my code to the name of your timer control.

    No, you don't need akhileshbc's code to wait for the start time. All you need to do is change lines 22 and 26 from "Now()" to whatever time you want processing to start.

    Because the timer only checks twice a second, the cpu load will be minimal. As in, it'll probably read as 0&#37; cpu usage.

  24. #24

    Thread Starter
    Junior Member
    Join Date
    Oct 2010
    Location
    Zagreb
    Posts
    29

    Re: How to calculate with date AND time in VB?

    I didn't have a timer control. I've put it and changed lines 22 and 26 to a specific time.

    And now timer works

    Thank You ! !

  25. #25
    PowerPoster Ellis Dee's Avatar
    Join Date
    Mar 2007
    Location
    New England
    Posts
    3,530

    Re: How to calculate with date AND time in VB?

    It'd probably be cleaner to change line 26 to:

    mdtmNext = mdtmStart

    This doesn't really change anything and so it isn't necessary, but it's a cleaner solution because if you ever decide to change it back to starting immediately, you only have to change the code in one place. (Line 22.)

    Otherwise, glad to hear it's working for you.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width