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

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

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

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. "log"
  7. "os"
  8. "time"
  9. )
  10. // Users 结构体包含一个用户数组
  11. type Users struct {
  12. Users []User `json:"users"`
  13. }
  14. // User 结构体包含姓名、类型和社交链接列表
  15. type User struct {
  16. Firstname string `json:"fname"`
  17. Secondname string `json:"lname"`
  18. Date string `json:"date"`
  19. }
  20. func main() {
  21. // 打开json文件
  22. jsonFile, err := os.Open("users.json")
  23. // 如果os.Open返回错误,则处理错误
  24. if err != nil {
  25. fmt.Println(err)
  26. }
  27. fmt.Println("成功打开users.json")
  28. // 延迟关闭jsonFile,以便稍后解析
  29. defer jsonFile.Close()
  30. // 将打开的json文件读取为字节数组
  31. byteValue, _ := ioutil.ReadAll(jsonFile)
  32. // 初始化Users数组
  33. var users Users
  34. // 将包含json文件内容的byteArray解组为上面定义的'users'
  35. json.Unmarshal(byteValue, &users)
  36. // 遍历users数组中的每个用户,并打印出用户类型、姓名和Facebook链接作为示例
  37. // 编写一个函数来列出今天生日的人。
  38. // var yr int
  39. for i := 0; i < len(users.Users); i++ {
  40. date, err := time.Parse("2006/01/02", users.Users[i].Date)
  41. if err != nil {
  42. log.Fatal(err)
  43. }
  44. fmt.Println(date)
  45. date1, err := time.Parse("2006-01-02", users.Users[i].Date)
  46. if err != nil {
  47. log.Fatal(err)
  48. }
  49. fmt.Println(date1)
  50. // 检查日期是否为闰年,例如:29不是闰年,但28是!
  51. if date.Day()%400 == 0 || (date.Day()%4 == 0 && date.Day()%100 != 0) {
  52. fmt.Println("用户名:", users.Users[i].Firstname)
  53. fmt.Println("用户姓氏:", users.Users[i].Secondname)
  54. fmt.Println("用户日期:", users.Users[i].Date)
  55. fmt.Println(users.Users[i].Date, "是闰年 ✨✨✨")
  56. } else if date1.Day()%400 == 0 || (date1.Day()%4 == 0 && date1.Day()%100 != 0) {
  57. fmt.Println("用户名:", users.Users[i].Firstname)
  58. fmt.Println("用户姓氏:", users.Users[i].Secondname)
  59. fmt.Println("用户日期:", users.Users[i].Date)
  60. fmt.Println(users.Users[i].Date, "是闰年 ✨✨✨")
  61. } else {
  62. fmt.Println("用户名:", users.Users[i].Firstname)
  63. fmt.Println("用户姓氏:", users.Users[i].Secondname)
  64. fmt.Println("用户日期:", users.Users[i].Date)
  65. fmt.Println(users.Users[i].Date, "不是闰年 &#128165;&#128165;&#128165;")
  66. }
  67. }
  68. }

.JSON文件

  1. {
  2. "users": [
  3. {
  4. "Fname": "Johnny",
  5. "Lname":"mane",
  6. "date":"1982/01/08"
  7. },
  8. {
  9. "Fname": "Wayne",
  10. "Lname":"Bruce",
  11. "date":"1965/01/30"
  12. },
  13. {
  14. "Fname": "Gaga",
  15. "Lname":"Lady",
  16. "date":"1986/03/28"
  17. },
  18. {
  19. "Fname": "radio",
  20. "Lname":"head",
  21. "date":"1988/02/29"
  22. },
  23. {
  24. "Fname": "Mario",
  25. "Lname":"torres",
  26. "date":"1996/09/28"
  27. },
  28. {
  29. "Fname": "robert",
  30. "Lname":"Alex",
  31. "date":"1991/12/01"
  32. },
  33. {
  34. "Fname": "Julia",
  35. "Lname":"sevak",
  36. "date":"1991-03-07"
  37. },
  38. {
  39. "Fname": "feb",
  40. "Lname":"robert",
  41. "date":"1995-01-31"
  42. }
  43. ]
  44. }

希望对你有帮助!

英文:

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

  1. package main
  2. import (
  3. &quot;encoding/json&quot;
  4. &quot;fmt&quot;
  5. &quot;io/ioutil&quot;
  6. &quot;log&quot;
  7. &quot;os&quot;
  8. &quot;time&quot;
  9. )
  10. // Users struct which contains
  11. // an array of users
  12. type Users struct {
  13. Users []User `json:&quot;users&quot;`
  14. }
  15. // User struct which contains a name
  16. // a type and a list of social links
  17. type User struct {
  18. Firstname string `json:&quot;fname&quot;`
  19. Secondname string `json:&quot;lname&quot;`
  20. Date string `json:&quot;date&quot;`
  21. }
  22. func main() {
  23. // Open our jsonFile
  24. jsonFile, err := os.Open(&quot;users.json&quot;)
  25. // if we os.Open returns an error then handle it
  26. if err != nil {
  27. fmt.Println(err)
  28. }
  29. fmt.Println(&quot;Successfully Opened users.json&quot;)
  30. // defer the closing of our jsonFile so that we can parse it later on
  31. defer jsonFile.Close()
  32. // read our opened xmlFile as a byte array.
  33. byteValue, _ := ioutil.ReadAll(jsonFile)
  34. // we initialize our Users array
  35. var users Users
  36. // we unmarshal our byteArray which contains our
  37. // jsonFile&#39;s content into &#39;users&#39; which we defined above
  38. json.Unmarshal(byteValue, &amp;users)
  39. // we iterate through every user within our users array and
  40. // print out the user Type, their name, and their facebook url
  41. // as just an example
  42. // write a function to list out the people whose birthday is today.
  43. // var yr int
  44. for i := 0; i &lt; len(users.Users); i++ {
  45. date, err := time.Parse(&quot;2006/01/02&quot;, users.Users[i].Date)
  46. if err != nil {
  47. log.Fatal(err)
  48. }
  49. fmt.Println(date)
  50. date1, err := time.Parse(&quot;2006-01-02&quot;, users.Users[i].Date)
  51. if err != nil {
  52. log.Fatal(err)
  53. }
  54. fmt.Println(date1)
  55. // check if the date is a leap year, ex: 29 is not a leap year but 28th is !
  56. if date.Day()%400 == 0 || (date.Day()%4 == 0 &amp;&amp; date.Day()%100 != 0) {
  57. fmt.Println(&quot;User First Name: &quot; + users.Users[i].Firstname)
  58. fmt.Println(&quot;User Second Name: &quot; + users.Users[i].Secondname)
  59. fmt.Println(&quot;User Date: &quot; + users.Users[i].Date)
  60. fmt.Println(users.Users[i].Date, &quot; is a Leap Year ✨✨✨ &quot;)
  61. } else if date1.Day()%400 == 0 || (date1.Day()%4 == 0 &amp;&amp; date1.Day()%100 != 0) {
  62. fmt.Println(&quot;User First Name: &quot; + users.Users[i].Firstname)
  63. fmt.Println(&quot;User Second Name: &quot; + users.Users[i].Secondname)
  64. fmt.Println(&quot;User Date: &quot; + users.Users[i].Date)
  65. fmt.Println(users.Users[i].Date, &quot; is a Leap Year ✨✨✨ &quot;)
  66. } else {
  67. fmt.Println(&quot;User First Name: &quot; + users.Users[i].Firstname)
  68. fmt.Println(&quot;User Second Name: &quot; + users.Users[i].Secondname)
  69. fmt.Println(&quot;User Date: &quot; + users.Users[i].Date)
  70. fmt.Println(users.Users[i].Date, &quot; is Not a Leap Year &#128165;&#128165;&#128165; &quot;)
  71. }
  72. }
  73. }

.JSON file

  1. {
  2. &quot;users&quot;: [
  3. {
  4. &quot;Fname&quot;: &quot;Johnny&quot;,
  5. &quot;Lname&quot;:&quot;mane&quot;,
  6. &quot;date&quot;:&quot;1982/01/08&quot;
  7. },
  8. {
  9. &quot;Fname&quot;: &quot;Wayne&quot;,
  10. &quot;Lname&quot;:&quot;Bruce&quot;,
  11. &quot;date&quot;:&quot;1965/01/30&quot;
  12. },
  13. {
  14. &quot;Fname&quot;: &quot;Gaga&quot;,
  15. &quot;Lname&quot;:&quot;Lady&quot;,
  16. &quot;date&quot;:&quot;1986/03/28&quot;
  17. },
  18. {
  19. &quot;Fname&quot;: &quot;radio&quot;,
  20. &quot;Lname&quot;:&quot;head&quot;,
  21. &quot;date&quot;:&quot;1988/02/29&quot;
  22. },
  23. {
  24. &quot;Fname&quot;: &quot;Mario&quot;,
  25. &quot;Lname&quot;:&quot;torres&quot;,
  26. &quot;date&quot;:&quot;1996/09/28&quot;
  27. },
  28. {
  29. &quot;Fname&quot;: &quot;robert&quot;,
  30. &quot;Lname&quot;:&quot;Alex&quot;,
  31. &quot;date&quot;:&quot;1991/12/01&quot;
  32. },
  33. {
  34. &quot;Fname&quot;: &quot;Julia&quot;,
  35. &quot;Lname&quot;:&quot;sevak&quot;,
  36. &quot;date&quot;:&quot;1991-03-07&quot; --&gt;
  37. },
  38. {
  39. &quot;Fname&quot;: &quot;feb&quot;,
  40. &quot;Lname&quot;:&quot;robert&quot;,
  41. &quot;date&quot;:&quot;1995-01-31&quot;. ---&gt;
  42. }
  43. ]
  44. }

答案1

得分: 2

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

  1. 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.:

  1. 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中格式化日期的示例,无需担心字符串日期:

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

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

  1. 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

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

You can then use the below function to format it.

  1. 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:

确定