Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Serialize Date to ISO-8601 string, deserialize ISO-8601 string to Date #155

Open
kpenergy opened this issue Jul 27, 2021 · 1 comment
Open

Comments

@kpenergy
Copy link

Is it possible to use this library to serialise a Date value to an ISO-8601 string?

for example, I want this:

class MyObject {
    @serializable /* Need to specify the target here?*/
    MyDate!: Date
}
const myObject = new MyObject();
myObject.MyDate = new Date();

const json = serialize(myObject);
console.log(json);

To output this:

'{"MyDate":"2021-07-27T14:39:15.915Z"}'

And then I want to be able to do the reverse of this; deserialze this JSON into an instance of MyObject, with MyDate properly instantiated.

const myNewObject = deserialize(MyObject, json);
console.log(myNewObject.MyDate.ToISOString()); 

should output this:

2021-07-27T14:39:15.915Z

I've tried declaring the @serializable attribute with date() in the constructor, which outputs the date as epoch as per the docs.

I've tried declaring the @serializable attribute using primitive() in the constructor, which I think should be valid based on this:

Indicates that this field contains a primitive value (or Date) which should be serialized literally to JSON.

But this throws the error:

Exception has occurred: Error: [serializr] this value is not primitive: Tue Jul 27 2021 15:51:19 GMT+0100 (British Summer Time)

Any help with this would be appreciated.

@andreaslarssen
Copy link

Don't think the package has support for this, but you can always use the custom() function to do the converting yourself.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants