Reputation: 73
I've been a programmer for only a few months, and I'm super new at Javascript, so help me out if there's a simpler way. I'm creating a drop down of months and a textbox of year. Is there a better way to do my month select box? And how can I format my date to yyyy-mm-dd? Thanks!
<div class="form-group">
<label for="month">Month:</label>
<select id="month">
<option value="0">January</option>
<option value="1">February</option>
<option value="2">March</option>
<option value="3">April</option>
<option value="4">May</option>
<option value="5">June</option>
<option value="6">July</option>
<option value="7">August</option>
<option value="8">September</option>
<option value="9">October</option>
<option value="10">November</option>
<option value="11">December</option>
</select>
</div>
<div class="form-group">
<label for="year">Year:</label>
<input type="text" id="year" value=""/>
</div>
<script>
$(document).ready(function() {
var budget_start_date = new Date(year, month, 1);
var budget_end_date;
$('#start_date').val(budget_start_date.toString('yyyy-MM-dd'))
$('#end_date').val(budget_end_date.toString('yyyy-MM-dd'))
};
</script>
Upvotes: 2
Views: 155
Reputation: 9550
An implementation of the date formatting:
/**
* Default format:yyyy-mm-dd hh:ii:ss
* @param string stamp Time in milliseconds
* @param string format Your desired format
* @param boolean zero With zero-prefix or not
*/
function format(timestamp, format, zero){
var stamp = Number(timestamp),
date = new Date(stamp), formatDate,
f = format ? format : "yyyy-mm-dd hh:ii:ss",
_d = (zero === undefined) ? l.format.zero : function(s){return s;};
var year = _d(date.getFullYear()),
month = _d(date.getMonth() + 1),
day = _d(date.getDate()),
hour = _d(date.getHours()),
minute = _d(date.getMinutes()),
second = _d(date.getSeconds());
formatDate = f.replace(/yyyy/i, year).replace(/mm/i, month).replace(/dd/i, day)
.replace(/hh/i, hour).replace(/ii/i, minute).replace(/ss/i, second);
return formatDate;
},
Upvotes: 0
Reputation: 81
Looks like you are trying to re-invent the wheel in this one, you are already using jQuery so you might as well use jQuery Date Picker, after you load the references you get a full functional calendar by doing $('#yourDateField').datepicker()
About the format part, you could use DataJS, then the format is simple as dt.toString('dd-MM-yyyy')
Upvotes: 2