strptime in Javascript

2019-07-11 12:36发布

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?

3条回答
地球回转人心会变
2楼-- · 2019-07-11 13:09

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()...

查看更多
我想做一个坏孩纸
3楼-- · 2019-07-11 13:16

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);   
查看更多
可以哭但决不认输i
4楼-- · 2019-07-11 13:29

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.

查看更多
登录 后发表回答