允许从星期日到星期五运行吗?

huangapple go评论67阅读模式
英文:

Allow to run from Sunday to Friday?

问题

以下是在Go语言中实现允许进程在特定时间段内运行的代码:

package main

import (
	"fmt"
	"time"
)

func main() {
	curDate := time.Now().Format("2006-01-02")
	myDate, _ := time.Parse("2006-01-02", curDate)

	if myDate.Weekday() == time.Sunday {
		if time.Now().Hour() < 15 {
			return
		}
	}

	if myDate.Weekday() == time.Friday {
		if time.Now().Hour() > 19 {
			return
		}
	}

	if myDate.Weekday() == time.Saturday {
		return
	}

	// 在此处编写要在特定时间段内运行的代码
	fmt.Println("Process is running...")
}

请注意,Go语言中的时间处理使用time包,代码中使用了time.Now()获取当前时间,time.Now().Hour()获取当前小时数,time.Parse()用于解析日期字符串。根据当前日期和时间,可以使用条件语句来控制进程的运行。在特定时间段内,可以编写要运行的代码,例如在注释中标记的位置。

英文:

The following PHP code that allows a process to only run between certain times. How would this be done in GoLang?

$curdate = date(&#39;Y-m-d&#39;);
$mydate=getdate(strtotime($curdate));
if ( $mydate[&#39;wday&#39;] === 0 ) {
  if ( date(&#39;H&#39;) &lt; 15 ) { exit; }; // This is for 0 Sunday!!!
}
if ( $mydate[&#39;wday&#39;] === 5 ) {
  if ( date(&#39;H&#39;) &gt; 19 ) { exit; }; // This is for 5 Friday!!!
}
if ( $mydate[&#39;wday&#39;] === 6 ) {
  exit;  // This is for 6 Saturday //
}

答案1

得分: 4

这段代码可以实现相同的功能:

now := time.Now()
day := now.Weekday()
hr  := now.Hour()

if day == 0 {
    if hr < 15 { os.Exit(0) }
} 
if day == 5 {
    if hr > 19 { os.Exit(0) }
}
if day == 6 {
    os.Exit(0)
}

类似地,每天都可以用一个整数(0-6)表示。

请注意,要使用 timeos,你需要调用以下代码:

import "time"
import "os"

有关Golang时间的更多信息,请参阅文档

英文:

This should do the same thing:

now := time.Now()
day := now.Weekday()
hr  := now.Hour()

if day == 0 {
	if hr &lt; 15 { os.Exit(0) }
} 
if day == 5 {
	if hr &gt; 19 { os.Exit(0) }
}
if day == 6 {
	os.Exit(0)
}

Where similarly, each day can be represented by an integer (0 - 6).

Note that to use time and os you will need to call

import &quot;time&quot;
import &quot;os&quot;

See the documentation for more about Golang time.

答案2

得分: 0

不要将 PHP 代码写成 Go 代码。写 Go 代码。例如,

package main

import (
	"os"
	"time"
)

func main() {
	now := time.Now()
	hour := now.Hour()
	switch now.Weekday() {
	case time.Sunday:
		if hour < 15 {
			os.Exit(0)
		}
	case time.Friday:
		if hour > 19 {
			os.Exit(0)
		}
	case time.Saturday:
		os.Exit(0)
	}
	// 做一些事情
}
英文:

Don't write PHP code as Go code. Write Go code. For example,

package main

import (
	&quot;os&quot;
	&quot;time&quot;
)

func main() {
	now := time.Now()
	hour := now.Hour()
	switch now.Weekday() {
	case time.Sunday:
		if hour &lt; 15 {
			os.Exit(0)
		}
	case time.Friday:
		if hour &gt; 19 {
			os.Exit(0)
		}
	case time.Saturday:
		os.Exit(0)
	}
	// Do Something
}

huangapple
  • 本文由 发表于 2017年5月8日 02:36:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/43835216.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定