Golang : Time slice or date sort and reverse sort example
Sorting time.Time
type and dates is pretty straight forward in Golang. Just curious why it is not included in the sort
package.
Here’s an example of sorting slice of time.Time
in Go.
package main
import (
"fmt"
"sort"
"time"
)
type timeSlice []time.Time
func (s timeSlice) Less(i, j int) bool { return s[i].Before(s[j]) }
func (s timeSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s timeSlice) Len() int { return len(s) }
var past = time.Date(2010, time.May, 18, 23, 0, 0, 0, time.Now().Location())
var present = time.Now()
var future = time.Now().Add(24 * time.Hour)
var dateSlice timeSlice = []time.Time{present, future, past}
func main() {
fmt.Println("Past : ", past)
fmt.Println("Present : ", present)
fmt.Println("Future : ", future)
fmt.Println("Before sorting : ", dateSlice)
sort.Sort(dateSlice)
fmt.Println("After sorting : ", dateSlice)
sort.Sort(sort.Reverse(dateSlice))
fmt.Println("After REVERSE sorting : ", dateSlice)
}
Sample output :
Past : 2010-05-18 23:00:00 +0800 SGT
Present : 2015-08-04 10:57:34.019368428 +0800 SGT
Future : 2015-08-05 10:57:34.019368476 +0800 SGT
Before sorting : [2015-08-04 10:57:34.019368428 +0800 SGT 2015-08-05 10:57:34.019368476 +0800 SGT 2010-05-18 23:00:00 +0800 SGT]
After sorting : [2010-05-18 23:00:00 +0800 SGT 2015-08-04 10:57:34.019368428 +0800 SGT 2015-08-05 10:57:34.019368476 +0800 SGT]
After REVERSE sorting : [2015-08-05 10:57:34.019368476 +0800 SGT 2015-08-04 10:57:34.019368428 +0800 SGT 2010-05-18 23:00:00 +0800 SGT]
Reference :
http://grokbase.com/t/gg/golang-nuts/136mm2bf2m/go-nuts-sort-timeslice
https://www.socketloop.com/tutorials/golang-sort-and-reverse-sort-a-slice-of-strings
See also : Golang : Sort and reverse sort a slice of strings
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+4.4k Adding Skype actions such as call and chat into web page examples
+6.6k Android Studio : Hello World example
+7.4k Golang : Mapping Iban to Dunging alphabets
+10.8k Golang : Web routing/multiplex example
+7.5k Golang : Example of how to detect which type of script a word belongs to
+12k Golang : How to check if a string starts or ends with certain characters or words?
+10.7k Golang : How to transmit update file to client by HTTP request example
+7k Golang : How to fix html/template : "somefile" is undefined error?
+9.9k Golang : Compare files modify date example
+11.8k Linux : How to install driver for 600Mbps Dual Band Wifi USB Adapter
+4.8k Linux/Unix/MacOSX : Find out which application is listening to port 80 or use which IP version
+20.2k Golang : Secure(TLS) connection between server and client