go的相關包time、os、rand、fmt

time

一、time包this

二、time.Time類型, 用來表示時間spa

三、取當前時間, now := time.Now()操作系統

四、time.Now().Day(),time.Now().Minute(),time.Now().Month(),time.Now().Year(),3d

second := now.Unix() //按秒計

五、格式化,fmt.Printf(「%02d/%02d%02d %02d:%02d:%02d」, now.Year()…)指針

package main

import(
    "time"
    "fmt" ) func testTime() { for { now := time.Now() fmt.Printf("type of now is:%T\n", now) year := now.Year() month := now.Month() day := now.Day() str := fmt.Sprintf("%04d-%02d-%02d %02d:%02d:%02d\n", year, month, day, now.Hour(), now.Minute(), now.Second()) fmt.Println(str) fmt.Printf("timestamp:%d\n", now.Unix()) //時間戳  } }

六、time.Duration 用來表示納秒 code

七、 一些常量量: orm

const (   blog

   Nanosecond Duration = 1 字符串

Microsecond= 1000 * Nanosecond //納秒string

Millisecond= 1000 * Microsecond //微妙

Second= 1000 * Millisecond //毫秒

Minute= 60 * Second 

Hour= 60 * Minute

package main

import(
    "time"
    "fmt" ) func testTimeConst() { fmt.Printf("Nanosecond :%d\n", time.Nanosecond) //1 fmt.Printf("Microsecond:%d\n", time.Microsecond) //1000 fmt.Printf("Millisecond:%d\n", time.Millisecond) //1000000 fmt.Printf("second :%d\n", time.Second) fmt.Printf("Minute :%d\n", time.Minute) fmt.Printf("Hour :%d\n", time.Hour) }

8. 格式化: 

now := time.Now() 

fmt.Println(now.Format(「02/1/2006 15:04:05」))    //02/1/2006 03:04:05   十二小時制

fmt.Println(now.Format(「2006/1/02 15:04:05」)) 

fmt.Println(now.Format(「2006/1/02」))

package main

import(
    "time"
    "fmt" ) func main() { now := time.Now() str := now.Format("2006-01-02 03:04:05") fmt.Printf("format result:%s\n", str) }

練習:寫 一個程序,統計一段代碼的執行耗時,單位精確到微秒 

package main

import(
    "time"
    "fmt" ) func main() { start := time.Now().UnixNano() //納秒爲單位
/* 業務代碼 */ time.Sleep(10*time.Millisecond) end := time.Now().UnixNano() cost := (end - start)/1000 fmt.Printf("cost:%dus\n", cost) }

  

os 

package main
import (
     "fmt"
     "os" ) func main() { var goos string = os.Getenv("OS") //操做系統的名字 fmt.Printf("The operating system is: %s\n", goos) path := os.Getenv("PATH") //GOPATH的路徑 fmt.Printf("Path is %s\n", path) } 

math/rand

View Code
View Code

 

fmt   

各類方法集合:

格式化輸出:

 
 
package main
import "fmt"
func main() {
var a int = 100
var b bool
c := 'a'

fmt.Printf("%+v\n", a) //相似%v,但輸出結構體時會添加字段名
fmt.Printf("%#v\n", b) //相應值的Go語法表示
fmt.Printf("%T\n", c) //值的類型的Go語法表示
fmt.Printf("90%%\n") //字面上的%
fmt.Printf("%t\n", b) //布爾值
fmt.Printf("%b\n", 100) //二進制
fmt.Printf("%f\n", 199.22) //浮點型,有小數點,但沒有指數
fmt.Printf("%q\n", "this is a test") //雙引號圍繞的字符字面值
fmt.Printf("%x\n", 39839333) //每一個字節用兩字符十六進制數表示(使用a-f)
fmt.Printf("%p\n", &a) //傳入指針,表示爲十六進制,並加上前導的0x
fmt.Printf("%c\n", 87) //相應Unicode碼所表示的字符

str := fmt.Sprintf("a=%d", a) // 將a轉化爲字符串
fmt.Printf("%q\n", str)
}

 格式化輸入:

 
 
package mainimport "fmt"var number intvar str stringfunc main() {   fmt.Scanf("%d", &number)   fmt.Scanf("%s", &str)   fmt.Println(number, str)}
相關文章
相關標籤/搜索