How to compare times of the day?
You can't compare a specific point in time (such as "right now") against an unfixed, recurring event (8am happens every day).
You can check if now is before or after today's 8am:
>>> import datetime
>>> now = datetime.datetime.now()
>>> today8am = now.replace(hour=8, minute=0, second=0, microsecond=0)
>>> now < today8am
True
>>> now == today8am
False
>>> now > today8am
False
C# best way to compare two time of the day
How about:
internal static bool IsTimeOver()
{
return DateTime.Now.TimeOfDay > _whenTimeIsOver;
}
Operator overloading is very helpful for date and time work :) You might also want to consider making it a property instead of a method.It's a slight pity that there isn't a
DateTime.CurrentTime
orTimeSpan.CurrentTime
to avoid DateTime.Now.TimeOfDay
(just as there's DateTime.Today
) but alas, no...I have a set of extension methods on int
in MiscUtil which would make the initialization of _whenTimeIsOver
neater - you'd use:
private static readonly TimeSpan _whenTimeIsOver = 16.Hours() + 25.Minutes();
It's not to everyone's tastes, but I like it... How to do date/time comparison
Use the time package to work with time information in Go.
Play example:Time instants can be compared using the Before, After, and Equal
methods. The Sub method subtracts two instants, producing a Duration.
The Add method adds a Time and a Duration, producing a Time.
package main
import (
"fmt"
"time"
)
func inTimeSpan(start, end, check time.Time) bool {
return check.After(start) && check.Before(end)
}
func main() {
start, _ := time.Parse(time.RFC822, "01 Jan 15 10:00 UTC")
end, _ := time.Parse(time.RFC822, "01 Jan 16 10:00 UTC")
in, _ := time.Parse(time.RFC822, "01 Jan 15 20:00 UTC")
out, _ := time.Parse(time.RFC822, "01 Jan 17 10:00 UTC")
if inTimeSpan(start, end, in) {
fmt.Println(in, "is between", start, "and", end, ".")
}
if !inTimeSpan(start, end, out) {
fmt.Println(out, "is not between", start, "and", end, ".")
}
}
Dart/Flutter How to compare two TimeOfDay times?
Convert it to a double then compare.
double toDouble(TimeOfDay myTime) => myTime.hour + myTime.minute/60.0
How to compare two times
**Your PC Note down time with millisecond that's why you are not able to get desired result **
If You Provide second in datetime obj then -\
from datetime import time, datetime
start = datetime(2020, 1 , 18, 9,30)
current_time = datetime.now()
start_str=str(start)
current_str=str(surrent_time)
if(start_str==current_str):
print(match)
**General Method **if we want to match particular part This is 23 hour format if you want 12 hour format you can find diff parameter answer
start = datetime(2020, 1 , 18, 9,30)
current = datetime.now()
start_year=start.strftime("%Y")
start_month=start.strftime("%m")
start_day=start.strftime("%H")
start_hours=start.strftime("%H")
start_min=start.strftime("%M")
print(start_year,start_month,start_day,start_hours,start_min)
current_year=current.strftime("%Y")
current_month=current.strftime("%m")
current_day=current.strftime("%H")
current_hours=current.strftime("%H")
current_min=current.strftime("%M")
print(current_year,current_month,current_day,current_hours,current_min)
if((start_year==current_year) and (start_month==current_month) and (start_day==current_day) and (start_hours==current_hours) and (start_min==current_min)):
print("match")
How can I compare time of the day between Date objects in Java 8?
You can use the compareTo
-Method of LocalTime
if you convert the Date
before.
Convert like this (found at https://www.baeldung.com/java-date-to-localdate-and-localdatetime):
public static LocalTime convertToLocalTimeViaInstant(Date dateToConvert) {
return dateToConvert.toInstant()
.atZone(ZoneId.systemDefault())
.toLocalTime();
}
and compare like this:time1.compareTo(time2);
If u want to use a method u can use the conversion like this:
public static int compareTimeOfDates(Date date1, Date date2) {
return convertToLocalTimeViaInstant(date1).compareTo(convertToLocalTimeViaInstant(date2));
}
Comparing date part only without comparing time in JavaScript
I'm still learning JavaScript, and the only way that I've found which works for me to compare two dates without the time is to use the setHours
method of the Date object and set the hours, minutes, seconds and milliseconds to zero. Then compare the two dates.
For example,
date1 = new Date()
date2 = new Date(2011,8,20)
date2
will be set with hours, minutes, seconds and milliseconds to zero, but date1 will have them set to the time that date1 was created. To get rid of the hours, minutes, seconds and milliseconds on date1 do the following:date1.setHours(0,0,0,0)
Now you can compare the two dates as DATES only without worrying about time elements. How do you compare just the time of a Date in Swift?
This is the route I took in the end, which makes it easy to compare just the time of a Date in swift
New Object Time:
class Time: Comparable, Equatable {
init(_ date: Date) {
//get the current calender
let calendar = Calendar.current
//get just the minute and the hour of the day passed to it
let dateComponents = calendar.dateComponents([.hour, .minute], from: date)
//calculate the seconds since the beggining of the day for comparisions
let dateSeconds = dateComponents.hour! * 3600 + dateComponents.minute! * 60
//set the varibles
secondsSinceBeginningOfDay = dateSeconds
hour = dateComponents.hour!
minute = dateComponents.minute!
}
init(_ hour: Int, _ minute: Int) {
//calculate the seconds since the beggining of the day for comparisions
let dateSeconds = hour * 3600 + minute * 60
//set the varibles
secondsSinceBeginningOfDay = dateSeconds
self.hour = hour
self.minute = minute
}
var hour : Int
var minute: Int
var date: Date {
//get the current calender
let calendar = Calendar.current
//create a new date components.
var dateComponents = DateComponents()
dateComponents.hour = hour
dateComponents.minute = minute
return calendar.date(byAdding: dateComponents, to: Date())!
}
/// the number or seconds since the beggining of the day, this is used for comparisions
private let secondsSinceBeginningOfDay: Int
//comparisions so you can compare times
static func == (lhs: Time, rhs: Time) -> Bool {
return lhs.secondsSinceBeginningOfDay == rhs.secondsSinceBeginningOfDay
}
static func < (lhs: Time, rhs: Time) -> Bool {
return lhs.secondsSinceBeginningOfDay < rhs.secondsSinceBeginningOfDay
}
static func <= (lhs: Time, rhs: Time) -> Bool {
return lhs.secondsSinceBeginningOfDay <= rhs.secondsSinceBeginningOfDay
}
static func >= (lhs: Time, rhs: Time) -> Bool {
return lhs.secondsSinceBeginningOfDay >= rhs.secondsSinceBeginningOfDay
}
static func > (lhs: Time, rhs: Time) -> Bool {
return lhs.secondsSinceBeginningOfDay > rhs.secondsSinceBeginningOfDay
}
}
Date Extension for easy access://Adds ability to just get the time from a date:
extension Date {
var time: Time {
return Time(self)
}
}
Example:let firstDate = Date()
let secondDate = firstDate
//Will return true
let timeEqual = firstDate.time == secondDate.time
Related Topics
Start a Flask Application in Separate Thread
How to Tell Pycharm What Type a Parameter Is Expected to Be
Does Python Evaluate If's Conditions Lazily
When to Use Get, Get_Queryset, Get_Context_Data in Django
How Dangerous Is Setting Self._Class_ to Something Else
Selenium Webdriver in Python - Files Download Directory Change in Chrome Preferences
_Getattr_ for Static/Class Variables
Why Do We Need to Call Zero_Grad() in Pytorch
How to Resolve a Tesseractnotfounderror
Handling of Duplicate Indices in Numpy Assignments
String with 'F' Prefix in Python-3.6
When Should an Attribute Be Private and Made a Read-Only Property
How to Get a Gcp Bearer Token Programmatically with Python