Reputation: 597
I'm trying to get the value of the input type "month" - 2 digit month and 2 digit year.
PROBLEM
Format correct, but returns wrong date.
CODE
$("#cardExpireDate").change(function() {
var expireDate = new Date ( $(this).val() );
//var expireDay = expireDate.getDate();
var expireMonth = expireDate.getMonth() + 1;
var expireYear = parseInt(expireDate.getFullYear().toString().substr(2,2), 10);
var expireDateMMYY = ([expireMonth, expireYear]).join('/');
//alert([expireMonth, expireYear].join('/'));
$("#summaryCardExpireDate").val( expireDateMMYY );
});
@import url(https://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700,800);
.container {width:400px; margin:0 auto;}
label {float:left; margin:10px 0; vertical-align:middle; line-height:30px;}
input {width:200px; height:30px; margin:10px; 0; vertical-align:middle; font-family:"Open Sans", sans-serif; font-size:15px; border:0; outline:0;}
#cardExpireDate {border:1px solid #999;}
#summaryCardExpireDate {border:0; border-bottom:1px solid #999;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="formField">
<input type="month" id="cardExpireDate" name="card_expire_date" placeholder="Expiration..." title="Card Expire Date" required="">
<label class="" for="cardExpireDate">Expiration Date:
</label>
<input type="text" id="summaryCardExpireDate">
<label class="" for="summaryCardExpireDate">Returned Value:
</label>
</div>
</div>
CODEPEN
http://codepen.io/zuhloobie/pen/ggWdLj
Thanks in advance :)
UPDATE
This is what I see on Google Chrome: Version 55.0.2883.87 m (64 bit):
Upvotes: 2
Views: 1288
Reputation: 11340
Debugging date object shows that date is Sun Jan 01 2017 03:00:00 GMT+0300 (RTZ 2 (зима))
. It is right the start of a month. Take a look at your localization, you must have not a UTC time. I would fix the issue just by adding 1 day to a date.
var expireDate = new Date ( $(this).val() );
expireDate.setDate(expireDate.getDate() + 1);
Looks like you are in western hemisphere of Earth. This will probably make it clear, why creating Date
object is so sensible: Javascript date object always one day off?
Upvotes: 1
Reputation: 31
If you went to have month value in two digits you have to change var expireMonth:
from : var expireMonth = expireDate.getMonth() + 1;
to : var expireMonth=('0'+(expireDate.getMonth()+1)).slice(-2);
It works fine :)
Upvotes: 1