0

I was looking for a way to get the month name and day-of-week name from a Date object in javascript and came across this post: Get month name from Date where David Storey pointed to the date.toLocaleString() method. At first it looked like this was working great. I could do something like this to get the month name without having to define an array:

var someDate = new Date(2018, 8, 28);
var locale = "en-us"
var month = someDate.toLocaleString(locale, { month: "short" }).toLowerCase();

that would give me a result of aug in the month variable. But I noticed a problem with this. Ultimately I was dropping the month and day-of-week values into hidden form fields that would get posted with the form. When the form posted I wasn't getting the expected values. For example, looking at the posted value for the month field, instead of aug I was getting %FDaug, and the same was true for the day-of-week value. But if I checked the values in the debugger prior to posting, they looked correct. I don't know where the %FD was coming from but it means I can't use this method unless there is some way to trim that off first. I looked at documentation for the function here but didn't see anything there related to this issue.

For now I'm back to using an array of month and day names and doing a lookup to get those. Anyone know why that extra ascii character is introduced when using Date.toLocaleString?

Here are screenshots from the browser debugger, I've tried this in IE, Edge, and Chrome. Chrome appears to be ok, but IE and Edge have this behavior. I haven't tried Firefox

the values before posting... debugger variables are ok

the posted values...

posted values are wrong

Community
  • 1
  • 1
AK3800
  • 2,138
  • 3
  • 23
  • 28
  • 1
    I think you're going to have to define an array or trim these chars off based on this post: https://stackoverflow.com/questions/25574963/ies-tolocalestring-has-strange-characters-in-results I'd suggest moment.js to handle dates if you can justify adding a dep for just dates: https://momentjs.com/ – Michael Curry Aug 31 '18 at 16:27
  • @MichaelCurry thank you for the suggestion. I went with the array option since I don't need to deal with different locales and didn't want to bring in a new library just for this. – AK3800 Sep 07 '18 at 15:48

0 Answers0