如何将 JSON 中的日期转换为普通日期以检查是否为闰年(GoLang)?

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

How to convert Date in Json to normal date to check if it is a leap year in GoLang?

问题

我正在尝试将JSON文件中的日期转换为我的.go脚本中的普通日期,我想检查它们是否是闰年,我已经完成了这部分,但我想将其转换为日期,但我不知道如何操作,我尝试使用strconv.Itoa(users.Users[i].Date),但它没有起作用!

如果有任何反馈或帮助,将不胜感激,谢谢!

当我尝试同时添加两种类型的日期格式时收到的错误消息为:2021/10/21 12:15:35 parsing time "1982/01/08" as "2006-01-02": cannot parse "/01/08" as "-"

以下是您提供的代码的翻译:

BD.go

package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"time"
)

// Users 结构体包含一个用户数组
type Users struct {
	Users []User `json:"users"`
}

// User 结构体包含姓名、类型和社交链接列表
type User struct {
	Firstname  string `json:"fname"`
	Secondname string `json:"lname"`
	Date       string `json:"date"`
}

func main() {

	// 打开json文件
	jsonFile, err := os.Open("users.json")
	// 如果os.Open返回错误,则处理错误
	if err != nil {
		fmt.Println(err)
	}

	fmt.Println("成功打开users.json")
	// 延迟关闭jsonFile,以便稍后解析
	defer jsonFile.Close()

	// 将打开的json文件读取为字节数组
	byteValue, _ := ioutil.ReadAll(jsonFile)

	// 初始化Users数组
	var users Users

	// 将包含json文件内容的byteArray解组为上面定义的'users'
	json.Unmarshal(byteValue, &users)

	// 遍历users数组中的每个用户,并打印出用户类型、姓名和Facebook链接作为示例
	// 编写一个函数来列出今天生日的人。
	// var yr int

	for i := 0; i < len(users.Users); i++ {
		date, err := time.Parse("2006/01/02", users.Users[i].Date)

		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(date)

		date1, err := time.Parse("2006-01-02", users.Users[i].Date)

		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(date1)

		// 检查日期是否为闰年,例如:29不是闰年,但28是!
		if date.Day()%400 == 0 || (date.Day()%4 == 0 && date.Day()%100 != 0) {
			fmt.Println("用户名:", users.Users[i].Firstname)
			fmt.Println("用户姓氏:", users.Users[i].Secondname)
			fmt.Println("用户日期:", users.Users[i].Date)
			fmt.Println(users.Users[i].Date, "是闰年 ✨✨✨")
		} else if date1.Day()%400 == 0 || (date1.Day()%4 == 0 && date1.Day()%100 != 0) {
			fmt.Println("用户名:", users.Users[i].Firstname)
			fmt.Println("用户姓氏:", users.Users[i].Secondname)
			fmt.Println("用户日期:", users.Users[i].Date)
			fmt.Println(users.Users[i].Date, "是闰年 ✨✨✨")
		} else {
			fmt.Println("用户名:", users.Users[i].Firstname)
			fmt.Println("用户姓氏:", users.Users[i].Secondname)
			fmt.Println("用户日期:", users.Users[i].Date)
			fmt.Println(users.Users[i].Date, "不是闰年 &#128165;&#128165;&#128165;")
		}
	}
}

.JSON文件

{
    "users": [
      {
        "Fname": "Johnny",
        "Lname":"mane",
        "date":"1982/01/08"
      },
      {
        "Fname": "Wayne",
        "Lname":"Bruce",
        "date":"1965/01/30"
      },
      {
        "Fname": "Gaga",
        "Lname":"Lady",
        "date":"1986/03/28"
      },
      {
        "Fname": "radio",
        "Lname":"head",
        "date":"1988/02/29"
      },
      {
        "Fname": "Mario",
        "Lname":"torres",
        "date":"1996/09/28"
      },
      
      {
        "Fname": "robert",
        "Lname":"Alex",
        "date":"1991/12/01"
      },
      {
        "Fname": "Julia",
        "Lname":"sevak",
        "date":"1991-03-07"
      },
      {
        "Fname": "feb",
        "Lname":"robert",
        "date":"1995-01-31"
      }
    ]
  }

希望对你有帮助!

英文:

I'm trying to convert the date in a json file to normal date in my .go script, i want to check if they are leap years or not, i already did this part, but i want to convert it to date, but i don't know how, i tried to use strconv.Itoa(users.Users[i].Date) but it didn't work !

Would appreciate any feedback or help, Thanks !

The error i received when i tried to add both types of date forms at the same time --> 2021/10/21 12:15:35 parsing time "1982/01/08" as "2006-01-02": cannot parse "/01/08" as "-"

BD.go

     package main
import (
&quot;encoding/json&quot;
&quot;fmt&quot;
&quot;io/ioutil&quot;
&quot;log&quot;
&quot;os&quot;
&quot;time&quot;
)
// Users struct which contains
// an array of users
type Users struct {
Users []User `json:&quot;users&quot;`
}
// User struct which contains a name
// a type and a list of social links
type User struct {
Firstname  string `json:&quot;fname&quot;`
Secondname string `json:&quot;lname&quot;`
Date       string `json:&quot;date&quot;`
}
func main() {
// Open our jsonFile
jsonFile, err := os.Open(&quot;users.json&quot;)
// if we os.Open returns an error then handle it
if err != nil {
fmt.Println(err)
}
fmt.Println(&quot;Successfully Opened users.json&quot;)
// defer the closing of our jsonFile so that we can parse it later on
defer jsonFile.Close()
// read our opened xmlFile as a byte array.
byteValue, _ := ioutil.ReadAll(jsonFile)
// we initialize our Users array
var users Users
// we unmarshal our byteArray which contains our
// jsonFile&#39;s content into &#39;users&#39; which we defined above
json.Unmarshal(byteValue, &amp;users)
// we iterate through every user within our users array and
// print out the user Type, their name, and their facebook url
// as just an example
// write a function to list out the people whose birthday is today.
// var yr int
for i := 0; i &lt; len(users.Users); i++ {
date, err := time.Parse(&quot;2006/01/02&quot;, users.Users[i].Date)
if err != nil {
log.Fatal(err)
}
fmt.Println(date)
date1, err := time.Parse(&quot;2006-01-02&quot;, users.Users[i].Date)
if err != nil {
log.Fatal(err)
}
fmt.Println(date1)
// check if the date is a leap year, ex: 29 is not a leap year but 28th is !
if date.Day()%400 == 0 || (date.Day()%4 == 0 &amp;&amp; date.Day()%100 != 0) {
fmt.Println(&quot;User First Name: &quot; + users.Users[i].Firstname)
fmt.Println(&quot;User Second Name: &quot; + users.Users[i].Secondname)
fmt.Println(&quot;User Date: &quot; + users.Users[i].Date)
fmt.Println(users.Users[i].Date, &quot; is a Leap Year ✨✨✨  &quot;)
} else if date1.Day()%400 == 0 || (date1.Day()%4 == 0 &amp;&amp; date1.Day()%100 != 0) {
fmt.Println(&quot;User First Name: &quot; + users.Users[i].Firstname)
fmt.Println(&quot;User Second Name: &quot; + users.Users[i].Secondname)
fmt.Println(&quot;User Date: &quot; + users.Users[i].Date)
fmt.Println(users.Users[i].Date, &quot; is a Leap Year ✨✨✨  &quot;)
} else {
fmt.Println(&quot;User First Name: &quot; + users.Users[i].Firstname)
fmt.Println(&quot;User Second Name: &quot; + users.Users[i].Secondname)
fmt.Println(&quot;User Date: &quot; + users.Users[i].Date)
fmt.Println(users.Users[i].Date, &quot; is Not a Leap Year &#128165;&#128165;&#128165; &quot;)
}
}
}

.JSON file

{
&quot;users&quot;: [
{
&quot;Fname&quot;: &quot;Johnny&quot;,
&quot;Lname&quot;:&quot;mane&quot;,
&quot;date&quot;:&quot;1982/01/08&quot;
},
{
&quot;Fname&quot;: &quot;Wayne&quot;,
&quot;Lname&quot;:&quot;Bruce&quot;,
&quot;date&quot;:&quot;1965/01/30&quot;
},
{
&quot;Fname&quot;: &quot;Gaga&quot;,
&quot;Lname&quot;:&quot;Lady&quot;,
&quot;date&quot;:&quot;1986/03/28&quot;
},
{
&quot;Fname&quot;: &quot;radio&quot;,
&quot;Lname&quot;:&quot;head&quot;,
&quot;date&quot;:&quot;1988/02/29&quot;
},
{
&quot;Fname&quot;: &quot;Mario&quot;,
&quot;Lname&quot;:&quot;torres&quot;,
&quot;date&quot;:&quot;1996/09/28&quot;
},
{
&quot;Fname&quot;: &quot;robert&quot;,
&quot;Lname&quot;:&quot;Alex&quot;,
&quot;date&quot;:&quot;1991/12/01&quot;
},
{
&quot;Fname&quot;: &quot;Julia&quot;,
&quot;Lname&quot;:&quot;sevak&quot;,
&quot;date&quot;:&quot;1991-03-07&quot; --&gt;
},
{
&quot;Fname&quot;: &quot;feb&quot;,
&quot;Lname&quot;:&quot;robert&quot;,
&quot;date&quot;:&quot;1995-01-31&quot;.  ---&gt; 
}
]
}

答案1

得分: 2

如果你将日期字段解组为字符串,你需要使用time.Parse函数解析它,使用与你的日期格式匹配的布局,例如:

date, err := time.Parse("2006/01/02", users.Users[i].Date)

或者,你可以直接使用json.UnmarshalJSON将其解组为time.Time字段,但是你需要一些额外的代码来支持你的自定义日期格式,如https://stackoverflow.com/questions/25087960/json-unmarshal-time-that-isnt-in-rfc-3339-format中所述。

英文:

If you unmarshal the date field into a string, you need to parse it with time.Parse using a given layout that matches your date format, e.g.:

date, err := time.Parse(&quot;2006/01/02&quot;, users.Users[i].Date)

Alternatively, you could unmarshal using json.UnmarshalJSON directly into a time.Time field, but you would need some additional code to support your custom date format as described in https://stackoverflow.com/questions/25087960/json-unmarshal-time-that-isnt-in-rfc-3339-format.

答案2

得分: 1

从GitHub上下载araddon timeparse库:

https://github.com/araddon/dateparse.git

以下是使用这个令人惊奇的包在golang中格式化日期的示例,无需担心字符串日期:

t, err := dateparse.ParseAny("3/1/2014")

然后可以使用以下函数进行格式化:

s := t.Format("02 Jan 2006")

你可以尝试使用上述包,它仍然存在一些特殊情况,但适用于大多数情况。

英文:

Download the araddon timeparse library from github

https://github.com/araddon/dateparse.git

Below is a sample to format date in golang with this amazing package without worrying about the string date

t, err := dateparse.ParseAny(&quot;3/1/2014&quot;)

You can then use the below function to format it.

 s:= t.Format(&quot;02 Jan 2006&quot;)

You can definitely try with the above package, it still has some corner cases but works for most of the cases.

huangapple
  • 本文由 发表于 2021年10月21日 14:21:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/69656822.html
匿名

发表评论

匿名网友

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

确定