q := datastore.NewQuery("Encounter").Filter("PatientID =", patientID).Order("CreatedDate").Order("-CreatedBy")
How can I query all the values except the values created today?
Add a filter by CreatedDate.
t := time.Now()
zone, _ := time.LoadLocation("Europe/Amsterdam")
day := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, zone)
q := datastore.NewQuery("Encounter").Filter("PatientID =", patientID).Filter("CreatedDate <", day).Order("CreatedDate").Order("-CreatedBy")
This only returns items older than today. If you need both older and newer than today, since there is no inequality in filters, you can fetch older and newer than today, then iterate through them and append the results.
Related
I am looking to display a time in a specific format for a particular country. My current code:
now := time.Now()
ogTime := time.Date(2022, 8, 1, 0, 0, 0, 0, now.Location())
loc, _ := time.LoadLocation("Asia/Singapore")
convertedTime := ogTime.In(loc)
fmt.Println(convertedTime)
This prints out 2022-08-01 08:00:00 +0800 +08
Is there a way to display 2022-07-31T16:00:00Z? Is it possible to remove the time offset and instead just have a Z? I have tried ogTime.Format(RFC3339) as well as something like ogTime.Format("2006-01-02 T15:04:05Z"), but neither work.
fmt.Println is using the Stringer()-implementation of time.Time to print the value as a string, which determines the formatting for you.
To set the format yourself, use time.Time.Format();
now := time.Now()
fmt.Println(now.Format(`2006-01-02T15:04:05Z07:00`))
A "Z" in the output without an offset means the time is in UTC. If you do not want to print the timezone, omit it from the format;
fmt.Println(convertedTime.Format("2006-01-02T15:04:05"))
2022-08-01T08:00:00
If you want to print in UTC convert the timezone before printing; fmt.Println(convertedTime.UTC().Format("2006-01-02T15:04:05Z07:00"))
2022-08-01T00:00:00Z
Printing a "Z" while the time is not in UTC would require you to concatenate it yourself, but would be silly;
fmt.Println(convertedTime.Format("2006-01-02T15:04:05") + "Z")
2022-08-01T08:00:00Z
If you want to provide local time and print it in UTC, provide your timezone when parsing the date
loc, _ := time.LoadLocation("Asia/Singapore")
ogTime := time.Date(2022, 8, 1, 0, 0, 0, 0, loc)
fmt.Println(ogTime.UTC().Format("2006-01-02T15:04:05Z07:00"))
2022-07-31T16:00:00Z
I have dates stored as timestamps in mongo, for example, 1564444800000000000. I want to check if a timestamp is between 2 dates - July 1, 2021 and July, 2021. I converted these 2 dates to timestamps using https://www.epochconverter.com/. I first fetched all records and while looping through the records, I did a check like so
cDate := 1564444800000000000
if cDate > 1625167488000 && cDate < 1627759488000 {
log.Fatal("found one!")
}
But this not seem to work as I get no matches. Is there a better way of doing this?
I mean just looking at the numbers:
cDate := 1564444800000000000
1625167488000
1627759488000
I don't see how one with six more digits than the one's it's supposed to be between would ever be between them. And even if we divided CDate by 1000000 it would be
cDate := 1564444800000
1625167488000
1627759488000
and it's still less than both of those, so it still wouldn't be between them. But that being said, you most likely do just need to divide cDate by 1000000 and your example is just not a good one (since 1564444800000 is July 29 2019)
I suggest to transform in a date then check with the before and after API, as example:
package main
import (
"fmt"
"time"
)
func main() {
cDate := int64(1564444800000000000)
firstJuly := time.Date(2019, 7, 1, 0, 0, 0, 0, time.UTC)
thrirtyOneJuly := time.Date(2019, 7, 31, 0, 0, 0, 0, time.UTC)
date := time.Unix(0, cDate)
// fmt.Println(date) //will print 2019-07-30 00:00:00 +0000 UTC
fmt.Println("Is July?", date.After(firstJuly) && date.Before(thrirtyOneJuly))
}
will print
Is July? true
See on playground
I have two times, t1 and t2.
To calculate the difference, I use,
diff := t2.sub(t1)
The above code returns the difference like 10m30s, 1h3m59s etc.
I need to create some conditions for the difference.
For example,
if diff <= 5m {
do this
}
if diff > 20m {
do that
}
My question is if there is any built-in way to compare the time difference.
My other option would be to parse returned diff with regex and then compare. But I was looking for some efficient ways like the sub which the time package offers.
t2.Sub(t1) returns a duration, and you can simply use the comparison operators, for example:
d, _ := time.ParseDuration("4m4s")
if d <= 5 * time.Second {
fmt.Println("<= than limit")
} else {
fmt.Println("> than limit")
}
Way 1: When we use sub to get the duration
A very simple alternative is to directly use the output of the sub function. The func sub returns time.Duration type. So just adding .Minutes() method with it would serve the purpose in my case.
t1 := time.Now()
time.Sleep(60011 * time.Millisecond)
t2 := time.Now()
timeDiff := t2.Sub(t1)
fmt.Println(timeDiff)
fmt.Printf("\nIn just minites: %.f\n", timeDiff.Minutes())
Playground
Way 2: When we have the duration in string
If we would have the "difference" as a string ("10m2s") type then I believe we need to use the ParseDuration function. From the godocs ParseDuration
From the doc,
ParseDuration parses a duration string. A duration string is a possibly signed sequence of decimal numbers, each with optional fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m". Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".
I am thinking of using it like the following,
t = "10h10m6s"
timeDiff, _ := time.ParseDuration(t)
numberOfHours := timeDiff.Hours()
numberOfMinutes := timeDiff.Minutes()
numberOfSeconds := timeDiff.Seconds()
numberofNanosec := timeDiff.Nanoseconds()
Find the example snippet on the playground
So in any of the above cases, we can use time.Minutes() to compare the duration.. As #gopher pointed out that to compare with any time range we do not need to convert it to any period of time (e,g Mintues(), Seconds()) but we can just compare with a required time period. As #Haris Osmanagić pointed out that this works for both of the output of ParseDuration and time.Sub() as they both returns time.Duration type. So we can do something like the following,
if timeDiff < 5 * time.Minutes() {
do something
} else if timeDiff > 5 * time.Minutes(){
do something else
} else {
do nothing
}
An example is on the playground.
Problem Overview:
I'm querying a "Sessions" collection for sessions with a UserID == string, this works fine. But when I try and OrderBy("DateCreated", Desc) which is of type timestamp I get 0 results
What I've tried:
I've checked the DB and the property I'm using which is called "DateCreated" and it's a valid timestamp type. All sessions data is generated in go with random date ranges.
Current Results:
returns 100 results (correct)
firstSessionQuery := db.Collection("Sessions").Where("UserID", "==", uid).Documents(ctx)
returns 0 results VS 100 (incorrect)
firstSessionQuery := db.Collection("Sessions").Where("UserID", "==", uid).OrderBy("DateCreated", firestore.Asc).Documents(ctx)
firstSessionQuery := db.Collection("Sessions").Where("UserID", "==", uid)
allDocs, err := firstSessionQuery.Documents(ctx).GetAll()
docsSorted := firstSessionQuery.OrderBy("DateCreated", firestore.Asc).Documents(ctx)
allDocsSorted, err := docsSorted.GetAll()
fmt.Printf("docs len: %v, docs sorted len: %v\n", len(allDocs), len(allDocsSorted))
the first %v returns 100, second %v returns 0
Expected results:
My expected results are 100 sessions sorted by date, either ascending or descending.
Here are db screenshots:
here is the DateCreated prop
Here is the UserID prop
Terminal fmt printout
That work for me in a similar context
db.collection("Sessions")
.orderBy("DateCreated", Query.Direction.ASCENDING)
It was user error:
I was mapping the data to a custom type Session struct{} and one of the props was set to int when it should have been string, I wasn't catching the err.
I get from input source timestamp and then I make time '00:00:00' for this timestamp. Now I need to get timestamp from object time
timestamp_int:= 1532009163
time := time.Date(
time.Unix(int64(timestamp_int), 0).UTC().Year(),
time.Unix(int64(timestamp_int), 0).UTC().Month(),
time.Unix(int64(timestamp_int), 0).UTC().Day(), 0, 0, 0, 0,
time.Unix(int64(timestamp_int), 0).UTC().Location())
new_time := time.Format("timestamp") //here i need to get new timestamp
You can get the timestamp in seconds by using the Unix method.
timestamp := 1532009163
t := time.Unix(int64(timestamp), 0)
newTimestamp := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.UTC).Unix()
fmt.Println(newTimestamp)
// 1531958400