`
vikeyxp
  • 浏览: 3622 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
最近访客 更多访客>>
社区版块
存档分类
最新评论

百度自动对时,baidutime.golang

阅读更多
package main

import (
	"fmt"
	//正则
	"regexp"
	//采集
	"net/http"
	"io/ioutil"
	
	"strings"
	"time"
	//格式转换
	"strconv"
	//外部shell
	"os/exec"
	//暂停;
	"os"
	"bufio"
)
func main() {
	url:="http://open.baidu.com/special/time/"
	fmt.Println(url)
	mydate,mynow:=regexp_time(url)
	fmt.Println(mydate);
	callbat("date "+mydate)
	fmt.Println(mynow);
	callbat("time "+mynow)
	fmt.Println("well done!")
	pause()
}

//网络对时;
func file_get_contents(url string) string{
    r, e := http.Get(url)
    if e != nil {
        panic("not connected!")
    }
    defer r.Body.Close()
    c, e := ioutil.ReadAll(r.Body)
    if e != nil {
        panic("http got nothing")
    }
    return string(c)
}
//正则取时间;
func regexp_time(url string)(string,string){
	html:=file_get_contents(url)
	r:= regexp.MustCompile(`window.baidu_time(.*);`)
	rs:=r.FindStringSubmatch(html);
	str:=strings.Replace(rs[1],"(","",-1)
	str=strings.Replace(str,")","",-1)
 	str=substr(str,0,10);//unix时间戳;
	time64,err:=strconv.ParseInt(str,10,64);
	if err != nil{
		panic("strconv.ParseInt fail!");
	}
	mytime:=time.Unix(time64,0);
	mydate:=mytime.Format("2006-01-02")
	mynow:=mytime.Format("03:04:05")
	return string(mydate),string(mynow)
}
//字符串截取;
func substr(str string, start, length int) string {
    rs := []rune(str)
    rl := len(rs)
    end := 0
    if start < 0 {
        start = rl - 1 + start
    }
    end = start + length
    if start > end {
        start, end = end, start
    }
    if start < 0 {
        start = 0
    }
    if start > rl {
        start = rl
    }
    if end < 0 {
        end = 0
    }
    if end > rl {
        end = rl
    }
    return string(rs[start:end])
}
//外部脚本;
func callbat(cmd string){
	out,err := exec.Command("cmd","/c",cmd).Output()
	if err != nil{
		panic(err)
	}
	fmt.Printf(string(out))
	return
}
//暂停
func pause(){
	bufio.NewReader(os.Stdin).ReadBytes('\n')
}

 

  • 大小: 3.9 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics