下面的程序使用解析函数从当前日期和时间获取年、月、日、小时、分钟和秒。Clock函数用于返回时间T指定的一天内的小时、分钟和秒。
示例代码:
package main
import (
"fmt"
"time"
)
func main() {
currentTime := time.Now()
fmt.Println("\n######################################\n")
fmt.Println(currentTime.Format("2006-01-02 15:04:05"))
fmt.Println("\n######################################\n")
timeStampString := currentTime.Format("2006-01-02 15:04:05")
layOut := "2006-01-02 15:04:05"
timeStamp, err := time.Parse(layOut, timeStampString)
if err != nil {
fmt.Println(err)
}
hr, min, sec := timeStamp.Clock()
fmt.Println("Year :", currentTime.Year())
fmt.Println("Month :", currentTime.Month())
fmt.Println("Day :", currentTime.Day())
fmt.Println("Hour :", hr)
fmt.Println("Min :", min)
fmt.Println("Sec :", sec)
fmt.Println("\n######################################\n")
year, month, day := time.Now().Date()
fmt.Println("Year :", year)
fmt.Println("Month :", month)
fmt.Println("Day :", day)
fmt.Println("\n######################################\n")
t := time.Now()
y := t.Year()
mon := t.Month()
d := t.Day()
h := t.Hour()
m := t.Minute()
s := t.Second()
n := t.Nanosecond()
fmt.Println("Year :",y)
fmt.Println("Month :",mon)
fmt.Println("Day :",d)
fmt.Println("Hour :",h)
fmt.Println("Minute :",m)
fmt.Println("Second :",s)
fmt.Println("Nanosec:",n)
}
输出:
######################################
2017-08-27 18:11:54
######################################
Year : 2017
Month : August
Day : 27
Hour : 18
Min : 11
Sec : 54
######################################
Year : 2017
Month : August
Day : 27
######################################
Year : 2017
Month : August
Day : 27
Hour : 18
Minute : 11
Second : 54
Nanosec: 319513100
在日常开发中我们需要展示各类不同需求的时间格式,以下是通常使用的时间格式输出方式。
示例代码:
package main
import (
"fmt"
"time"
)
func main() {
currentTime := time.Now()
fmt.Println("Current Time in String: ", currentTime.String())
fmt.Println("MM-DD-YYYY : ", currentTime.Format("01-02-2006"))
fmt.Println("YYYY-MM-DD : ", currentTime.Format("2006-01-02"))
fmt.Println("YYYY.MM.DD : ", currentTime.Format("2006.01.02 15:04:05"))
fmt.Println("YYYY#MM#DD {Special Character} : ", currentTime.Format("2006#01#02"))
fmt.Println("YYYY-MM-DD hh:mm:ss : ", currentTime.Format("2006-01-02 15:04:05"))
fmt.Println("Time with MicroSeconds: ", currentTime.Format("2006-01-02 15:04:05.000000"))
fmt.Println("Time with NanoSeconds: ", currentTime.Format("2006-01-02 15:04:05.000000000"))
fmt.Println("ShortNum Month : ", currentTime.Format("2006-1-02"))
fmt.Println("LongMonth : ", currentTime.Format("2006-January-02"))
fmt.Println("ShortMonth : ", currentTime.Format("2006-Jan-02"))
fmt.Println("ShortYear : ", currentTime.Format("06-Jan-02"))
fmt.Println("LongWeekDay : ", currentTime.Format("2006-01-02 15:04:05 Monday"))
fmt.Println("ShortWeek Day : ", currentTime.Format("2006-01-02 Mon"))
fmt.Println("ShortDay : ", currentTime.Format("Mon 2006-01-2"))
fmt.Println("Short Hour Minute Second: ", currentTime.Format("2006-01-02 3:4:5"))
fmt.Println("Short Hour Minute Second: ", currentTime.Format("2006-01-02 3:4:5 PM"))
fmt.Println("Short Hour Minute Second: ", currentTime.Format("2006-01-02 3:4:5 pm"))
}
输出:
Current Time in String: 2017-07-04 00:47:20.1424751 +0530 IST
MM-DD-YYYY : 07-04-2017
YYYY-MM-DD : 2017-07-04
YYYY.MM.DD : 2017.07.04 00:47:20
YYYY#MM#DD {Special Character} : 2017#07#04
YYYY-MM-DD hh:mm:ss : 2017-07-04 00:47:20
Time with MicroSeconds: 2017-07-04 00:47:20.142475
Time with NanoSeconds: 2017-07-04 00:47:20.142475100
ShortNum Month : 2017-7-04
LongMonth : 2017-July-04
ShortMonth : 2017-Jul-04
ShortYear : 17-Jul-04
LongWeekDay : 2017-07-04 00:47:20 Tuesday
ShortWeek Day : 2017-07-04 Tue
ShortDay : Tue 2017-07-4
Short Hour Minute Second: 2017-07-04 12:47:20
Short Hour Minute Second: 2017-07-04 12:47:20 AM
Short Hour Minute Second: 2017-07-04 12:47:20 am
以下是计算两个时间之间之差的方法,具体到天,时,分,秒。
示例代码:
package main
import (
"fmt"
"time"
)
func main() {
loc, _ := time.LoadLocation("UTC")
now := time.Now().In(loc)
fmt.Println("\nToday : ", loc, " Time : ", now)
pastDate := time.Date(2015, time.May, 21, 23, 10, 52, 211, time.UTC)
fmt.Println("\n\nPast : ", loc, " Time : ", pastDate) //
fmt.Printf("###############################################################\n")
diff := now.Sub(pastDate)
hrs := int(diff.Hours())
fmt.Printf("Diffrence in Hours : %d Hours\n", hrs)
mins := int(diff.Minutes())
fmt.Printf("Diffrence in Minutes : %d Minutes\n", mins)
second := int(diff.Seconds())
fmt.Printf("Diffrence in Seconds : %d Seconds\n", second)
days := int(diff.Hours() / 24)
fmt.Printf("Diffrence in days : %d days\n", days)
fmt.Printf("###############################################################\n\n\n")
futureDate := time.Date(2019, time.May, 21, 23, 10, 52, 211, time.UTC)
fmt.Println("Future : ", loc, " Time : ", futureDate) //
fmt.Printf("###############################################################\n")
diff = futureDate.Sub(now)
hrs = int(diff.Hours())
fmt.Printf("Diffrence in Hours : %d Hours\n", hrs)
mins = int(diff.Minutes())
fmt.Printf("Diffrence in Minutes : %d Minutes\n", mins)
second = int(diff.Seconds())
fmt.Printf("Diffrence in Seconds : %d Seconds\n", second)
days = int(diff.Hours() / 24)
fmt.Printf("Diffrence in days : %d days\n", days)
}
输出:
Today : UTC Time : 2017-08-27 05:15:53.7106215 +0000 UTC
Past : UTC Time : 2015-05-21 23:10:52.000000211 +0000 UTC
###############################################################
Diffrence in Hours : 19878 Hours
Diffrence in Minutes : 1192685 Minutes
Diffrence in Seconds : 71561101 Seconds
Diffrence in days : 828 days
###############################################################
Future : UTC Time : 2019-05-21 23:10:52.000000211 +0000 UTC
###############################################################
Diffrence in Hours : 15185 Hours
Diffrence in Minutes : 911154 Minutes
Diffrence in Seconds : 54669298 Seconds
Diffrence in days : 632 days
示例代码:
package main
import (
"fmt"
"time"
)
func main() {
t := time.Now()
z, _ := t.Zone()
fmt.Println("ZONE : ", z, " Time : ", t) // local time
location, err := time.LoadLocation("EST")
if err != nil {
fmt.Println(err)
}
fmt.Println("ZONE : ", location, " Time : ", t.In(location)) // EST
loc, _ := time.LoadLocation("UTC")
now := time.Now().In(loc)
fmt.Println("ZONE : ", loc, " Time : ", now) // UTC
loc, _ = time.LoadLocation("MST")
now = time.Now().In(loc)
fmt.Println("ZONE : ", loc, " Time : ", now) // MST
}
输出:
ZONE : IST Time : 2017-08-26 22:12:31.3763932 +0530 IST
ZONE : EST Time : 2017-08-26 11:42:31.3763932 -0500 EST
ZONE : UTC Time : 2017-08-26 16:42:31.3773933 +0000 UTC
ZONE : MST Time : 2017-08-26 09:42:31.3783934 -0700 MST
Weekday返回t指定的星期几。YearDay返回t指定的一年中的某一天,非闰年的范围为 [1,365],闰年的范围为 [1,366]。
示例代码:
package main
import (
"fmt"
"time"
)
func main() {
t := time.Now() // 2024 01 03
fmt.Println(t.YearDay())
fmt.Println(t.Weekday())
// 年度,第几周year, week := t.ISOWeek()
fmt.Printf("year: %v\n", year)
// Prints the week number
fmt.Printf("week: %d\n", week)
}
输出:
3
Wednesday
year: 2024
week: 1
首先,需要配置时区,然后根据时区转换时间,LoadLocation返回具有给定名称的Location。
示例代码:
package main
import (
"fmt"
"time"
)
func main() {
t := time.Now()
fmt.Println("Location : ", t.Location(), " Time : ", t) // local time
location, err := time.LoadLocation("America/New_York")
if err != nil {
fmt.Println(err)
}
fmt.Println("Location : ", location, " Time : ", t.In(location)) // America/New_York
loc, _ := time.LoadLocation("Asia/Shanghai")
now := time.Now().In(loc)
fmt.Println("Location : ", loc, " Time : ", now) // Asia/Shanghai
}
输出:
Location : Local Time : 2017-08-26 21:04:56.1874497 +0530 IST
Location : America/New_York Time : 2017-08-26 11:34:56.1874497 -0400 EDT
Location : Asia/Shanghai Time : 2017-08-26 23:34:56.1884498 +0800 CST
您想知道特定地理区域(例如加拿大、另一个国家或国家集团,甚至可能是整个世界)的Twitter趋势。Twitter的Trends API使你能够获取由Where On Earth(WOE)ID指定的地理区域的热门话题,该ID最初由Geo Planet定义,然后由Yahoo!
这是使用Twitter API获取位置附近趋势的Web应用程序的基本示例。
https://api.twitter.com/1.1/trends/place.json返回特定WOOID的前50个热门主题(如果有可用的热门信息)。与所有其他API一样,它将热门主题作为JSON数据返回,这些数据可以转换为标准Golang对象,然后使用列表推导式或类似技术进行操作。
在http://dev.twitter.com/apps的Twitter帐户下注册应用程序,并获取所需的凭据(使用者密钥、使用者密钥、访问令牌和访问令牌密钥),OAuth应用程序需要这些凭据才能获得帐户访问权限。
安装软件包:
go get github.com/dghubble/oauth1
软件包oauth1提供了OAuth 1规范的Go实现,允许最终用户授权客户端(即消费者)代表他/她访问受保护的资源。
示例代码:main.go
能够处理GET和POST请求的函数viewHashTagHandler。ParseFiles创建一个新模板,并从hash_tags.html文件中解析模板定义。
package main
import (
"encoding/json"
"fmt"
"github.com/dghubble/oauth1"
"html/template"
"io/ioutil"
"net/http"
"strings"
)
func getHashTags(country string) []string {
var listHashTags []string
consumerKey := "xxxxxxxxxxxxxxxxxxx"
consumerSecret := "xxxxxxxxxxxxxxxxxxx"
accessToken := "xxxxxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxx"
accessSecret := "xxxxxxxxxxxxxxxxxxx"
if consumerKey == "" || consumerSecret == "" || accessToken == "" || accessSecret == "" {
panic("Missing required environment variable")
}
config := oauth1.NewConfig(consumerKey, consumerSecret)
token := oauth1.NewToken(accessToken, accessSecret)
httpClient := config.Client(oauth1.NoContext, token)
path := "https://api.twitter.com/1.1/trends/place.json?id=" + country
resp, _ := httpClient.Get(path)
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
var JSON = strings.TrimLeft(string(body), "[")
JSON = strings.TrimRight(JSON, "]")
var info map[string]interface{}
json.Unmarshal([]byte(JSON), &info)
trends := info["trends"].([]interface{})
for _, element := range trends {
if trendList, ok := element.(map[string]interface{}); ok {
for key, value := range trendList {
// Filter hashtags started with #
if strings.Contains(key, "name") && strings.Contains(value.(string), "#") {
listHashTags = append(listHashTags, value.(string))
}
}
}
}
return listHashTags
}
func main() {
http.HandleFunc("/", viewHashTagHandler)
http.ListenAndServe(":8080", nil)
}
func viewHashTagHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.Error(w, "404 not found.", http.StatusNotFound)
return
}
switch r.Method {
case "GET":
getPage, _ := template.ParseFiles("hash_tags.html")
getPage.Execute(w, r)
case "POST":
var country string
if err := r.ParseForm(); err != nil {
fmt.Fprintf(w, "ParseForm() err: %v", err)
return
}
country = r.FormValue("country")
tags := getHashTags(country)
postPage, _ := template.ParseFiles("hash_tags.html")
postPage.Execute(w, tags)
default:
fmt.Fprintf(w, "Unable to get result.")
}
}
示例代码:hash_tags.html
<html>
<head>
<title>Trending hash tags</title>
</head>
<body>
<form method="POST" action="/">
<select name="country">
<option value="23424848">India</option>
<option value="455830">Brazil</option>
<option value="3369">Canada</option>
<option value="1">Global</option>
</select>
<button type="submit">Show Trends</button>
</form>
<ul>
{{ range $key, $value := . }}
<li>{{ $value }}</li>
{{ end }}
</ul>
</body>
</html>
运行程序:
go run main.go
这将在您机器上的端口8080上的Web服务器上开发一个静态网站。这也会启动您的浏览器导航到http://localhost:8080。