From 8b7cfa4e8fdbe990281e05787239086f1220dc32 Mon Sep 17 00:00:00 2001 From: ravellan Date: Tue, 29 Dec 2020 01:39:33 +0100 Subject: [PATCH] Add Time() method to MQMD type --- ibmmq/ibmmq_test.go | 37 +++++++++++++++++++++++++++++++++++++ ibmmq/mqiMQMD.go | 26 ++++++++++++++++++++++++++ 2 files changed, 63 insertions(+) diff --git a/ibmmq/ibmmq_test.go b/ibmmq/ibmmq_test.go index db0a938..7313515 100644 --- a/ibmmq/ibmmq_test.go +++ b/ibmmq/ibmmq_test.go @@ -16,7 +16,9 @@ limitations under the License. package ibmmq import ( + "errors" "testing" + "time" ) // Tests for mqistr.go @@ -289,3 +291,38 @@ func TestRoundTo4(t *testing.T) { } } } + +func TestMQMDTime(t *testing.T) { + testDateTime, _ := time.Parse(time.RFC3339, "2015-12-14T07:00:00.99Z") + + // correct time + md := &MQMD{ + PutDate: "20151214", + PutTime: "07000099", + } + got, err := md.Time() + if err != nil { + t.Errorf("%s%s: expected nil error, got %v", md.PutDate, md.PutTime, err) + } + if got != testDateTime { + t.Errorf("%s%s: expected %v, got %v", md.PutDate, md.PutTime, testDateTime, got) + } + + // fail time parsing + md = &MQMD{ + PutDate: "bad date", + PutTime: "07000099", + } + got, err = md.Time() + var parseErr *time.ParseError + if !errors.As(err, &parseErr) { + t.Errorf("%s%s: expected time.ParseError{}, got %T", md.PutDate, md.PutTime, err) + } + + // empty fields + md = NewMQMD() + got, err = md.Time() + if err != ErrMDEmptyTime { + t.Errorf("empty fields: expected ErrMQMDTimeIsNil, got %v", err) + } +} diff --git a/ibmmq/mqiMQMD.go b/ibmmq/mqiMQMD.go index 451e00c..9e756c0 100644 --- a/ibmmq/mqiMQMD.go +++ b/ibmmq/mqiMQMD.go @@ -30,6 +30,8 @@ import "C" import ( "bytes" + "errors" + "time" ) /* @@ -103,6 +105,30 @@ func NewMQMD() *MQMD { return md } +// Go time package reference date time as +// concatenated date and time from MD +const mqmdGoRefTime = "20060102150405.99" + +// ErrMDEmptyTime is returned from the MQMD.Time() method +// if the PutTime field is empty +var ErrMDEmptyTime = errors.New("PutTime field in MQMD is empty") + +// Time returns the MQMD PutDate and PutTime as time.Time +func (md *MQMD) Time() (time.Time, error) { + if len(md.PutTime) != 8 { + return time.Time{}, ErrMDEmptyTime + } + + // separate fractions of a second with a dot + s := md.PutDate + md.PutTime[:6] + "." + md.PutTime[6:] + t, err := time.Parse(mqmdGoRefTime, s) + if err != nil { + return time.Time{}, err + } + + return t, nil +} + func checkMD(gomd *MQMD, verb string) error { mqrc := C.MQRC_NONE