Handlebars-Net / Handlebars.Net.Helpers

Handlebars.Net helpers in the categories: 'Boolean', 'Constants', 'Enumerable', 'Environment', 'Math', 'Regex', 'String', 'DateTime' and 'Url'.
MIT License
40 stars 15 forks source link

Add DateTime.Format #81

Closed natelaff closed 1 year ago

natelaff commented 1 year ago

I wrote a customer helper for formatting DateTime values (when they start as a string so you have to parse them first). a DateTime.Format seems like it would be useful, which of course is why I wrote it.

Would you want a PR on this? Is there a reason it doesn't already exist? String.Format only works if you're passing in a DateTime value that's already that type.

StefH commented 1 year ago

@natelaff So you want to format a DateTime (pass as a string?)

Like

{{DateTime.Format \"2020-04-15T23:59:58.0000000\" \"yyyy-MMM-dd\"}}
natelaff commented 1 year ago

Yes, that's correct. If you're using just plain JSON as a dynamic object, DateTime is just a string obviously. So I have to convert it then can format it.

Its basically just the String.Format code but does the DateTime.TryParse first.

StefH commented 1 year ago

Like this?

https://github.com/Handlebars-Net/Handlebars.Net.Helpers/pull/82

natelaff commented 1 year ago

@StefH yeah that's pretty much it. Tests against time only values like "00:00", "23:59", might be good because I also run into Time only things which this also handles, but yeah that's the gist of this! Thanks!

StefH commented 1 year ago

In case you use only "00:00" or"23:59", wouldn't that be a timespan instead of datetime?

natelaff commented 1 year ago

@StefH technically yes, but I use DateTime for these because I also have a dynamic culture. So by using short time code "t" as a format I can get the proper value display for a time for that IFormatProvider. TimeSpan doesn't have such a short code (that I recall anyways)

So I can do: {{DateTime.Format data.textValue "t"}}

And get like 2:35 PM for en-US and whatever else for the other cultures.

StefH commented 1 year ago

I did add another test for that 23:59

Can I merge this PR?

natelaff commented 1 year ago

Yeah that's great thank you!

Currently I only do this on DateTime but I can easily see in my scenario doing it for decimal (to format currency in culture format). Just some potential ideas for other helpers :)

StefH commented 1 year ago

OK. I'll merge this PR.

In case you want to create other builders, you know now how to build and test it.