Home > Backend Development > Golang > Use time.Parse to parse the different times before and after

Use time.Parse to parse the different times before and after

WBOY
Release: 2024-02-05 22:33:08
forward
540 people have browsed it

Use time.Parse to parse the different times before and after

Question content

I need to receive a time as a string, parse it, and then render it as a string again:

package main

import ("fmt"; "time")

func main() {
  const timelayout = "mon, jan 2, 2006 15:04 pm"
  sourcetime :=      "mon, apr 7, 2025 7:36 pm"
  mytime, err := time.parse(timelayout, sourcetime)
  if err != nil { panic(err) }
  fmt.printf("\t\tsourcetime = \"%s\"\n mytime.format(timelayout) = \"%s\"\n",
    sourcetime, mytime.format(timelayout))
}
Copy after login

This is my expected output:

sourcetime = "mon, apr 7, 2025 7:36 pm"
 mytime.format(timelayout) = "mon, apr 7, 2025 7:36 pm"
Copy after login

But I received this strange output:

sourceTime = "Mon, Apr 7, 2025 7:36 PM"
 myTime.Format(timeLayout) = "Mon, Apr 7, 2025 19:36 PM"
Copy after login

I didn't change something in the variable, so why am I receiving different results for the same layout? I shouldn't change this time layout. But again I need to receive the source string as result.


Correct answer


Your time layout uses the 24 hour clock (e.g. 15:04 instead of 3:04), so when you format it you will Get 19 instead of 7. If you want a 12 hour format, your time layout would be "Monday, January 2, 2006 3:04 PM"

The above is the detailed content of Use time.Parse to parse the different times before and after. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template