-
Oct 20th, 2010, 10:28 AM
#1
Thread Starter
Junior Member
[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
-
Oct 20th, 2010, 10:42 AM
#2
Re: How to calculate with date AND time in VB?
DateDiff function can handle that.
-
Oct 20th, 2010, 11:07 AM
#3
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
-
Oct 20th, 2010, 11:51 AM
#4
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.
-
Oct 20th, 2010, 12:01 PM
#5
Re: How to calculate with date AND time in VB?
Originally Posted by Morris_Zg
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:
If IsDate(Text1.Text) Then
Seconds = DateDiff("s", Text1.Text, Now())
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.
-
Oct 20th, 2010, 01:24 PM
#6
Thread Starter
Junior Member
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(??) ?
-
Oct 20th, 2010, 01:29 PM
#7
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.
-
Oct 20th, 2010, 01:35 PM
#8
Thread Starter
Junior Member
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
?
-
Oct 20th, 2010, 02:15 PM
#9
Re: How to calculate with date AND time in VB?
-
Oct 21st, 2010, 03:30 PM
#10
Thread Starter
Junior Member
Re: How to calculate with date AND time in VB?
thanks
-
Oct 21st, 2010, 03:33 PM
#11
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'.
-
Oct 22nd, 2010, 03:12 AM
#12
Thread Starter
Junior Member
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?
-
Oct 22nd, 2010, 03:48 AM
#13
Re: How to calculate with date AND time in VB?
Originally Posted by Morris_Zg
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:
Option Explicit
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Dim bolExit As Boolean
Dim lngTotalmSec As Long
Dim lngCurrentmSec As Long
Private Sub Command1_Click()
lngTotalmSec = 1000 '~~~ Total time to sleep
lngCurrentmSec = 0 '~~~ Holds how much time slept
Do While (lngCurrentmSec < lngTotalmSec) '~~~ Loop until the total time is reached
If bolExit = True Then '~~~ Check if the user wants to exit the sleeping process
bolExit = False
MsgBox "Hey...!!!"
Exit Do
Else '~~~ Otherwise, sleep for a few millisecs
lngCurrentmSec = lngCurrentmSec + 10
Sleep 10
DoEvents '~~~ This will prevent the "Not Responding" message
End If
Loop
MsgBox "Huuahh!! I had a great sleep "
End Sub
'~~~ If user wants to exit the sleep
Private Sub Command2_Click()
bolExit = True
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,...
-
Oct 22nd, 2010, 06:14 AM
#14
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:
Option Explicit
Private mdtmWake As Date
Private Sub Command1_Click()
' Sleep for 10 seconds
mdtmWake = DateAdd("s", 10, Now())
Timer1.Enabled = True
End Sub
Private Sub Timer1_Timer()
If mdtmWake > Now() Then Exit Sub
Timer1.Enabled = False
' Do the "wake up" code here
MsgBox "I'm awake!"
End Sub
-
Oct 23rd, 2010, 04:09 AM
#15
Thread Starter
Junior Member
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)?
-
Oct 23rd, 2010, 10:33 AM
#16
Re: How to calculate with date AND time in VB?
Something like this would do it:
vb Code:
Option Explicit
Private mdtmStart As Date
Private mdtmEnd As Date
Private mlngInterval As Long
Private Sub Command1_Click()
' Validate
If Val(txtInterval.Text) <= 0 Then
MsgBox "Interval must be greater than zero", vbInformation, "Notice"
txtInterval.SetFocus
Exit Sub
End If
If Not IsDate(txtEnd.Text) Then
MsgBox "Invalid end time", vbInformation, "Notice"
txtEnd.SetFocus
Exit Sub
End If
' Begin loop
mdtmStart = Now()
mdtmEnd = CDate(txtEnd.Text)
mlngInterval = Val(txtInterval.Text) ' Interval in seconds
Timer1.Interval = 500
Timer1.Enabled = True
End Sub
Private Sub Timer1_Timer()
If Now() >= mdtmEnd Then
Timer1.Enabled = False
MsgBox "End time reached. Loop finished.", vbInformation, "Notice"
Exit Sub
End If
If Now() - mdtmStart < mlngInterval Then Exit Sub
mdtmStart = Now()
Timer1.Enabled = False
SomeAction
Timer1.Enabled = True
End Sub
Private Sub SomeAction()
' The "some action" that gets done every specific interval of time
' Should probably rename this function (And its call in the Timer1_Timer event)
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.
-
Oct 24th, 2010, 03:06 AM
#17
Thread Starter
Junior Member
Re: How to calculate with date AND time in VB?
Originally Posted by Ellis Dee
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.
-
Oct 24th, 2010, 10:12 AM
#18
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.
-
Oct 24th, 2010, 10:58 AM
#19
Thread Starter
Junior Member
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.
-
Oct 24th, 2010, 12:08 PM
#20
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:
Option Explicit
Private mdtmStart As Date
Private mdtmNext As Date
Private mdtmEnd As Date
Private mlngInterval As Long
Private mlngIteration As Long
Private Sub Command1_Click()
' Validate
If Val(txtInterval.Text) <= 0 Then
MsgBox "Interval must be greater than zero", vbInformation, "Notice"
txtInterval.SetFocus
Exit Sub
End If
If Not IsDate(txtEnd.Text) Then
MsgBox "Invalid end time", vbInformation, "Notice"
txtEnd.SetFocus
Exit Sub
End If
' Begin loop
mdtmStart = Now()
mdtmEnd = CDate(txtEnd.Text)
mlngInterval = Val(txtInterval.Text) * 60 ' Interval in seconds
mlngIteration = 0
mdtmNext = Now()
Timer1.Interval = 500
Timer1.Enabled = True
End Sub
Private Sub Timer1_Timer()
If Now() >= mdtmEnd Then
Timer1.Enabled = False
MsgBox "End time reached. Loop finished.", vbInformation, "Notice"
Exit Sub
End If
If mdtmNext > Now() Then Exit Sub
mlngIteration = mlngIteration + 1
mdtmNext = DateAdd("s", mlngIteration * mlngInterval, mdtmStart)
Timer1.Enabled = False
SomeAction
Timer1.Enabled = True
End Sub
Private Sub SomeAction()
' The "some action" that gets done every specific interval of time
' Should probably rename this function (And its call in the Timer1_Timer event)
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.
-
Oct 24th, 2010, 01:23 PM
#21
Thread Starter
Junior Member
Re: How to calculate with date AND time in VB?
Originally Posted by Ellis Dee
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?
-
Oct 24th, 2010, 02:05 PM
#22
Thread Starter
Junior Member
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?
-
Oct 24th, 2010, 02:25 PM
#23
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% cpu usage.
-
Oct 27th, 2010, 02:35 PM
#24
Thread Starter
Junior Member
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 ! !
-
Oct 28th, 2010, 04:52 AM
#25
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|