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

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

WBOY
WBOYforward
2024-02-05 22:33:08512browse

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))
}

This is my expected output:

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

But I received this strange output:

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

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!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete