strptime in Javascript

2019-07-11 12:30发布

问题:

I have a date input field that allows the user to enter in a date and I need to validate this input (I already have server side validation), but the trick is that the format is locale dependent. I already have a system for translating the strptime format string to the the user's preference and I would like to use this same format for validating on the Javascript side.

Any ideas or links to a strptime() implementation in Javascript?

回答1:

After a few days of googling I found this implementation which, although not complete, seems to handle all of the cases I have right now.



回答2:

I've just added our php.js implementation of strptime(); I've tested it a bit, but it needs further unit testing. Anyhow, feel free to give it a shot; it should cover everything that PHP does (except for not yet supporting the undocumented %E... (alternative locale format) specifiers).

Note that it also depends on our implementation of setlocale() and array_map()...

  • https://github.com/kvz/phpjs/blob/master/functions/strings/setlocale.js
  • https://github.com/kvz/phpjs/blob/master/functions/array/array_map.js


回答3:

Here is an example function that duplicates most of the functionality of strptime. The JavaScript date object generally will parse any date string you throw at it so you don't have to worry to much about that. So once you have a date object based off of your string you just push each element into a JS object and return it. This site has a good reference to the properties of the JavaScript date object: http://www.javascriptkit.com/jsref/date.shtml

        function strptime(dateString){
            var myDate = new Date(dateString);
            return {tm_sec:myDate.getSeconds(), 
                            tm_min: myDate.getMinutes(), 
                            tm_hour: myDate.getHours(), 
                            tm_mday: myDate.getDate(),
                            tm_mon: myDate.getMonth(), 
                            tm_year: myDate.getFullYear().toString().substring(2), 
                            tm_wday: myDate.getDay()};

        }

        var dateString = "October 12, 1988 13:14:00";       
        dateObj = strptime(dateString);
        document.write("d:" + dateObj.tm_min + "/" + dateObj.tm_hour + "/" + dateObj.tm_mday + "/" + dateObj.tm_mon + "/" + dateObj.tm_year);