最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to turn character date into integer JavaScript - Stack Overflow

programmeradmin3浏览0评论

I need a way to turn my 2 character string dates (i.e. '04/10/2010' & '05/24/2010') into an integers to see if one is greater than the other. If the user enters an end date that is less than the begin date I need to popup an "invalid date range" error.

I need a way to turn my 2 character string dates (i.e. '04/10/2010' & '05/24/2010') into an integers to see if one is greater than the other. If the user enters an end date that is less than the begin date I need to popup an "invalid date range" error.

Share Improve this question edited Apr 29, 2010 at 12:48 Crescent Fresh 117k27 gold badges157 silver badges140 bronze badges asked Apr 29, 2010 at 12:23 sadmicrowavesadmicrowave 41k34 gold badges115 silver badges184 bronze badges 4
  • @DouweM In my opinion ( Java.syntax LIKE JavaScript.syntax ) === TRUE – Jacob Relkin Commented Apr 29, 2010 at 12:33
  • @Jacob Java.libraries != JavaScript.libraries; Java.libraries.contains(jquery) == false; – C. Ross Commented Apr 29, 2010 at 12:35
  • @DouweM - very true, sorry--mistype – sadmicrowave Commented Apr 29, 2010 at 12:36
  • @Jacob That doesn't make it right to use the term "Java" in a question that's really about JavaScript ;) – Douwe Maan Commented Apr 29, 2010 at 12:37
Add a ment  | 

3 Answers 3

Reset to default 5

From what you posted your real problem is:

I need to see if one date is greater than another in javascript/jquery.

If so all you need to use is the Javascript Date object (how to page here).

You can use it as follows:

var dateTextA = '04/10/2010';
var dateTextB = '05/24/2010';
var dateA = new Date(dateTextA);
var dateB = new Date(dateTextB);
if (dateA < dateB){
    alert("Your date is out of range!");
}

Note: Above code has been tested and works in IE7.

If you really feel you need an integer value, you can use the UTC function to get that.

The problem is Date.parse('04/10/2010') returns a timestamp (integer) for April 10 in the US and 4 October most other places.

It is best to use a less ambiguous format - if you are taking user input, give the user a calendar, menu, or three label inputs, then build the date from that.

3 inputs:

new Date(+fullyearinput, monthinput-1, +dateinput)

If Date won't parse what you are looking for, Datejs provides a lot of syntactic sugar to make your life easier.

To pare two dates, all you need to do is turn your strings into Date objects and then use the greater than, less than, or equality operators. Javascript provides Date parison natively.

发布评论

评论列表(0)

  1. 暂无评论