Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullable time.Time

Tags:

null

time

go

I have a struct that I intend to populate with a database record, one of the datetime columns is nullable:

type Reminder struct {     Id         int     CreatedAt  time.Time     RemindedAt *time.Time     SenderId   int     ReceiverId int } 

Since pointers can be nil, I've made RemindedAt a pointer, but this will require the code to know the difference between the At variables. Is there a more elegant way to handle this?

like image 991
tlehman Avatar asked Jul 03 '14 23:07

tlehman


People also ask

Is nullable DateTime?

By default DateTime is not nullable because it is a Value Type, using the nullable operator introduced in C# 2, you can achieve this.

What is nil value for time time?

The zero value of type Time is January 1, year 1, 00:00:00.000000000 UTC. As this time is unlikely to come up in practice, the IsZero method gives a simple way of detecting a time that has not been initialized explicitly.

How to create nullable DateTime property in c#?

Using the DateTime nullable type, you can assign the null literal to the DateTime type. A nullable DateTime is specified using the following question mark syntax.


2 Answers

You can use pq.NullTime, or with Go 1.13, you can now use the standard library's sql.NullTime type.

From lib/pq on github:

type NullTime struct {     Time  time.Time     Valid bool // Valid is true if Time is not NULL }  // Scan implements the Scanner interface. func (nt *NullTime) Scan(value interface{}) error {     nt.Time, nt.Valid = value.(time.Time)     return nil }  // Value implements the driver Valuer interface. func (nt NullTime) Value() (driver.Value, error) {     if !nt.Valid {         return nil, nil     }     return nt.Time, nil } 
like image 61
Dmitri Goldring Avatar answered Sep 28 '22 11:09

Dmitri Goldring


I like the NullTime example from lib/pq. I tweaked it this way so the NullTime can be treated like a Time...

type NullTime struct {     time.Time     Valid bool } 
like image 30
FogleBird Avatar answered Sep 28 '22 10:09

FogleBird