'How to decode Flutter iso8601 DateTime to Go Api RFC3339 pgtype.Date and pgtype.Timestamptz

In my Go API I'm trying to use json decode to parse the following json.

{"contract_id":0,"date_established":"2022-04-03T00:00:00.000","expiry_date":null,"extension_expiry_date":null,"description":"fffff"}

I get an error:

parsing time "\"2022-04-03T00:00:00.000\"" as "\"2006-01-02T15:04:05Z07:00\"": cannot parse "\"" as "Z07:00"

How can I fix this error?

This is my struct:

// Contract model
type Contract struct {
    ContractId          *int       `json:"contract_id"`
    CompanyId           *int       `json:"company_id"`
    DateEstablished     *time.Time `json:"date_established"`
    ExpiryDate          *time.Time `json:"expiry_date"`
    ExtensionExpiryDate *time.Time `json:"extension_expiry_date"`
    Description         *string    `json:"description"`
}

Here is my code:

func (rs *appResource) contractCreate(w http.ResponseWriter, r *http.Request) {

    var contract Contract

    decoder := json.NewDecoder(r.Body)

    err = decoder.Decode(&contract)


Solution 1:[1]

Go uses RFC 3339 for encoding time, if you control the json being produced you just need to change 2022-04-03T00:00:00.000 to 2022-04-03T00:00:00.000Z.

For instance this works.

type Contract struct {
    ContractId          *int       `json:"contract_id"`
    CompanyId           *int       `json:"company_id"`
    DateEstablished     *time.Time `json:"date_established"`
    ExpiryDate          *time.Time `json:"expiry_date"`
    ExtensionExpiryDate *time.Time `json:"extension_expiry_date"`
    Description         *string    `json:"description"`
}

func main() {
    body := `{"contract_id":0,"date_established":"2022-04-03T00:00:00.000Z","expiry_date":null,"extension_expiry_date":null,"description":"fffff"}`

    var contract Contract
    reader := strings.NewReader(body)
    decoder := json.NewDecoder(reader)
    err := decoder.Decode(&contract)
    if err != nil {
        fmt.Println("Error: ", err)
    } else {
        fmt.Printf("Contract: %+v\n", contract)
    }
}

If you don't control the json, you need to write a custom unmarshal method.

Solution 2:[2]

This is the solution I finally implemented in Flutter using pgtype.Date and pgtype.DateTimestamptz in my Go api and column types DATE and DATETIME in Postgresql. I was unable to use a pointer with this data type.

First I created a helper in Flutter like this:

import 'package:intl/date_symbol_data_local.dart';
import 'package:intl/intl.dart';

extension DateTimeExtension on DateTime {
  String format([String pattern = 'dd/MM/yyyy', String? locale]) {
    if (locale != null && locale.isNotEmpty) {
      initializeDateFormatting(locale);
    }
    return DateFormat(pattern, locale).format(this);
  }

  String formatDbDateTime(
      [String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", String? locale]) {
    if (locale != null && locale.isNotEmpty) {
      initializeDateFormatting(locale);
    }
    return DateFormat(pattern, locale).format(this);
  }

  String formatDbDate([String pattern = 'yyyy-MM-dd', String? locale]) {
    if (locale != null && locale.isNotEmpty) {
      initializeDateFormatting(locale);
    }
    return DateFormat(pattern, locale).format(this);
  }

  String formatLocalDate([String pattern = 'dd MMMM yyyy', String? locale]) {
    if (locale != null && locale.isNotEmpty) {
      initializeDateFormatting(locale);
    }
    return DateFormat(pattern, locale).format(this);
  }

  String formatLocalDateTime(
      [String pattern = 'dd MMMM yyyy h:mm a', String? locale]) {
    if (locale != null && locale.isNotEmpty) {
      initializeDateFormatting(locale);
    }
    return DateFormat(pattern, locale).format(this);
  }
}

I used this in my Flutter models to format the date for my Go Api:

if (planAcceptedDate != null) {
  data['plan_accepted_date'] = planAcceptedDate!.formatDbDateTime();
} else {
  data['plan_accepted_date'] = null;
}

if (invoiceDate != null) {
  data['invoice_date'] = invoiceDate!.formatDbDate();
} else {
  data['invoice_date'] = null;
}

and in my Flutter view form I use it like this:

        Container(
          padding: EdgeInsets.all(8.0),
          child: Text(
            _matter.planAcceptedDate == null
                ? ''
                : _matter.planAcceptedDate!.formatLocalDateTime(),
            style: TextStyle(
              color: appTextColor,
              fontWeight: FontWeight.normal,
              fontSize: _user.fontsize,
            ),
          ),
        ),
        Container(
          padding: EdgeInsets.all(8.0),
          child: Text(
            _matter.invoiceDate == null
                ? ''
                : _matter.invoiceDate!.formatLocalDate(),
            style: TextStyle(
              color: appTextColor,
              fontWeight: FontWeight.normal,
              fontSize: _user.fontsize,
            ),
          ),
        ),

My Go struct looks like this:

PlanAcceptedDate pgtype.Timestamptz `json:"plan_accepted_date"`
InvoiceDate      pgtype.Date        `json:"invoice_date"`

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 javiyu
Solution 2