Date formatting options using Javascript - javascript

I have this code that updates a calendar widget and input field, while validating the date. We want the user to be able to input any type of m-d-y format (m.d.y, m-d-y, and so on). The problem is the YUI calendar widget only accepts the m/d/y format. All others it returns as NaN. I have tried a couple ways to format the date, but can't get anything that seems to work. I would like to be able to do this with out a lot of overblown code. Does anyone have any suggestions as to the best approach here? Here is my code:
//CALENDAR --------------------------------------------------------------------------------
var initCal = function(calendarContainer){
if(YAHOO.env.getVersion("calendar")){
var txtDate = Dom.get("dateOfLoss");
var myDate = new Date();
var day = myDate.getDate();
var month = myDate.getMonth() +1;
var year = myDate.getFullYear() -1;
var newDate = month + "/" + day + "/" + year;
function handleSelect(type, args, obj){
var dates = args[0];
var date = dates[0];
var year = date[0], month = date[1], day = date[2];
txtDate.value = month + "/" + day + "/" + year;
aCal.hide();
}
function updateCal(){
if (!(txtDate.value.match(/((\d{2})|(\d))\/|\-((\d{2})|(\d))\/|\-((\d{4})|(\d{2}))/))) {
alert("Enter date in mm/dd/yy or mm/dd/yyyy format.");
}
else {
if (txtDate.value != "") {
aCal.select(txtDate.value);
var selectedDates = aCal.getSelectedDates();
if (selectedDates.length > 0) {
var firstDate = selectedDates[0];
aCal.cfg.setProperty("pagedate", (firstDate.getMonth() + 1) + "/" + firstDate.getFullYear());
aCal.render();
}
else {
alert("Date of Loss must be within the past year.");
}
}
}
}
var aCal = new YAHOO.widget.Calendar(null, calendarContainer, {
mindate: newDate,
maxdate: new Date(),
title: "Select Date",
close: true
});
aCal.selectEvent.subscribe(handleSelect, aCal, true);
aCal.render();
Event.addListener("update", "click", updateCal);
Event.addListener(txtDate, "change", function(e){
updateCal();
});
// Listener to show the 1-up Calendar when the button is clicked
// Hide Calendar if we click anywhere in the document other than the calendar
Event.on(document, "click", function(e){
var el = Event.getTarget(e);
if(Dom.hasClass(el, "calendarButton"))
aCal.show();
else if (Dom.hasClass(el, "link-close") || !Dom.isAncestor(calendarContainer, el))
aCal.hide();
});
}
else {
var successHandler = function() {
initCal(calendarContainer);
};
OURPLACE.loadComponent("calendar", successHandler);
}
};

Did you tried http://www.datejs.com/?
Maybe you can define some patterns and test agaist the input.
How can I convert string to datetime with format specification in JavaScript?

var updateCal = function(){
if (!(txtDate.value.match(/^(0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.]\d\d+$/))) {
return;
}
//else if ((txtDate.value.match(/^(0?[1-9]|1[012])[- .](0?[1-9]|[12][0-9]|3[01])[- .]\d\d+$/))) {
//}
else {
var changedDate = txtDate.value;
changedDate = changedDate.replace(/[. -]/g, "/");
txtDate.value = changedDate;
badClaimDate = claimDateWithinPastYear();
aCal.select(changedDate);
I used a RegEx to determine which, if any, delimiters needed to be replaced and simply used .replace.

Related

JS if else condition based on if div element changed > then populate data fields

I would like to create a simple if / else statement with JS. That would check if a div element has changed, before populating JSON data fields / variables that pull from dynamically changed HTML.
I do not want to use the DOMSubtreeModified. As it's depreciated..
Below is the started logic, I have. But it looks like I'll have to scrap the DOMSubtreeModified out for a method that is not depreciating.
The question / problem is: How to re-write not using the above depreciated technique, and how to nest my data array, where it will only pull / populate based on first checking my if (condition) Cheers for any pointers.
var element = document.querySelector('.username'); // username div wrapper
//if {
element.addEventListener('DOMSubtreeModified', function() { // detect if div element changes
var date = new Date();
var month = date.getUTCMonth() + 1;
var day = date.getUTCDate();
var year = date.getUTCFullYear();
var time = date.toLocaleTimeString();
var formattedDate = month + '/' + day + '/' + year;
console.log(time); // 7:01:21 PM
console.log(formattedDate); // 3/15/2016
}, false);
// change something on element
setTimeout(function() {
element.dataset.username = 'bar';
}, 3000);
// json object with captured data fields
var NewUserSession = [{
currentusername: $('.username').text(),
referrer: document.referrer,
loggedintime: $(formattedDate),
}];
//}
//
//else {
//
//
//}
You can use MutationObserver and watch for data-username changes
var element = document.querySelector('.username'); // username div wrapper
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.attributeName = 'data-username') {
var date = new Date();
var month = date.getUTCMonth() + 1;
var day = date.getUTCDate();
var year = date.getUTCFullYear();
var time = date.toLocaleTimeString();
var formattedDate = month + '/' + day + '/' + year;
snippet.log(time); // 7:01:21 PM
snippet.log(formattedDate); // 3/15/2016
}
});
});
var config = {
attributes: true,
attributeFilter: ['data-username']
};
// pass in the target node, as well as the observer options
observer.observe(element, config);
// change something on element
setTimeout(function() {
element.dataset.username = 'bar';
}, 1000);
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<div class="username"></div>

Kendo UI Grid - Filter - Date Range

Filtering a column by date range works nice with solution that i've found in SO
How to define a Kendo grid Column filter between two dates? - proposed by MWinstead
But
"The only problem with this solution is that if you only select the End Date and apply the filter, the next time you open the filter menu, the Begin Date will get populated with the End Date you entered and the LTE operator will be selected, which will be changed by the jQuery code, resulting in a wrong filter"
Question asked by ataravati in the same thread
How we can resolve this issue ?
The soltion is to provide the Begin Date with null value, even if the user hasn't selected it.
But, we must take control of submit button...
function grid_filterMenuInit(e) {
var currentFieldName = e.field;
if(currentFieldName === "yourFieldDate") {
console.info("ignoring this field: <" + currentFieldName + ">");
return;
}
console.info("performing this field: <" + currentFieldName + ">");
var filterSubmit = e.container.find("[type=submit]:eq(0)");
$(filterSubmit).click(function() {
var searchDateAfter = e.container.find("input:eq(0)");
var searchDateAfter1 = $(searchDateAfter).val();
var searchDateBefore = e.container.find("input:eq(1)");
var searchDateBefore1 = $(searchDateBefore).val();
var gridDatasource = $("#yourGridId").data("kendoGrid").dataSource;
var jsDateBefore = null;
var jsDateAfter = null;
// we must convert kendoDateTime to JavaScript DateTime object
// in my case the date time format is : yyyy/MM/dd HH:mm:ss
if (typeof searchDateBefore1 !== 'undefined') {
jsDateBefore = newJsDate(searchDateBefore1);
}
if (typeof searchDateAfter1 !== 'undefined') {
jsDateAfter = newJsDate(searchDateAfter1);
}
var previousFilter = gridDatasource.filter();
var previousFilters = new Array();
var newFilters = new Array();
// storing the previous filters ...
if (typeof previousFilter === 'object' && previousFilter.hasOwnProperty("filters")) {
previousFilters = previousFilter.filters;
for (var i=0 ; i<previousFilters.length ; i++) {
if (previousFilters[i].field !== currentFieldName) {
if (newFilters.length == 0) {
newFilters = [previousFilters[i]];
}
else {
newFilters.push(previousFilters[i]);
}
}
}
}
// this is the soltion : we must provide the first filter, even if the user has not provide the begin date
// and the value will be : null
if (newFilters.length == 0) {
newFilters = [{field: currentFieldName, operator: "gte", value: jsDateAfter }];
}
else {
newFilters.push ({field: currentFieldName, operator: "gte", value: jsDateAfter });
}
if (jsDateBefore !== null) {
newFilters.push ({field: currentFieldName, operator: "lte", value: jsDateBefore });
}
gridDatasource.filter (newFilters);
$(".k-animation-container").hide();
// to stop the propagation of filter submit button
return false;
});
}
function newJsDate(dateTime) {
if (dateTime === null ||
typeof dateTime === 'undefined' ||
dateTime === "") {
return null;
}
var dateTime1 = dateTime.split(" ");
var date = dateTime1[0];
var time = dateTime1[1];
var date1 = date.split("/");
var time1 = time.split(":");
var year = parseInt(date1[0], 10);
var month = parseInt(date1[1], 10);
month = month - 1;
var day = parseInt(date1[2], 10);
var hour = parseInt(time1[0], 10);
var minute = parseInt(time1[1], 10);
var second = parseInt(time1[2], 10);
var jsDate = new Date(year, month, day,
hour, minute, second);
return jsDate;
}

How to sum days to some date

I have an input with some date value and I want to sum 60 days to that that and put that val into other input. How can I do that?
Something like 2012-12-17 in first input and 2013-02-15 in second input
<td width="148"><input name="USER_joindate" id="USER_joindate" type="text" readonly="readonly" value="2012-12-17"></td>
<td><input name="EndPeriodExperience" id="EndPeriodExperience" type="text" readonly="readonly"></td>
$( document ).ready(function() {
$('#USER_joindate').on('change', function() {
....magic ...
});
});
download moment.js from http://momentjs.com/ and try this:
$(document).ready(function() {
$('#USER_joindate').on('change', function() {
// get the value of USER_joindate
var dateString = $(this).val();
// validate the date format inside USER_joindate
if (dateString.match(/^[0-9]{2}-[0-9]{2}-[0-9]{4}$/g)) {
// create a new date object using moment.js
var dateObj = moment(dateString);
// add 60 days to the date
dateObj.add(60, 'days');
// fill EndPeriodExperience with the new date
$("#EndPeriodExperience").val(dateObj.format("YYYY-MM-DD"));
}
});
});
I just find the way, check the fiddle:
$( document ).ready(function() {
$("#USER_joindate").on("change", function(){
var date = new Date($("#USER_joindate").val()),
days = parseInt($("#days").val(), 10);
if(!isNaN(date.getTime())){
date.setDate(date.getDate() + 61);
//2012-12-17
$("#EndPeriodExperience").val(date.toInputFormat());
} else {
alert("Fecha Invalida");
$("#USER_joindate").focus();
}
});
Date.prototype.toInputFormat = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString();
var dd = this.getDate().toString();
return yyyy + "-" + (mm[1]?mm:"0"+mm[0]) + "-" + (dd[1]?dd:"0"+dd[0]);
};
});
Thanks to all for your answers!

Multiple date picker - months jumping problems

Iam using a jquery multiple datepicker calendar. When i go to month of april and clicks the date, the datepicker restores to march.
var lastMDPupdate = '2012-03-28';
$(function() {
// Version //
//$('title').append(' v' + latestMDPver);
$('.mdp-version').text('v' + latestMDPver);
$('#mdp-title').attr('title', 'last update: ' + lastMDPupdate);
// Documentation //
$('i:contains(type)').attr('title', '[Optional] accepted values are: "allowed" [default]; "disabled".');
$('i:contains(format)').attr('title', '[Optional] accepted values are: "string" [default]; "object".');
$('#how-to h4').each(function () {
var a = $(this).closest('li').attr('id');
$(this).wrap('<'+'a href="#'+a+'"></'+'a>');
});
$('#demos .demo').each(function () {
var id = $(this).find('.box').attr('id') + '-demo';
$(this).attr('id', id)
.find('h3').wrapInner('<'+'a href="#'+id+'"></'+'a>');
});
// Run Demos
$('.demo .code').each(function() {
eval($(this).attr('title','NEW: edit this code and test it!').text());
this.contentEditable = true;
}).focus(function() {
if(!$(this).next().hasClass('test'))
$(this)
.after('<button class="test">test</button>')
.next('.test').click(function() {
$(this).closest('.demo').find('.box').removeClass('hasDatepicker').empty();
eval($(this).prev().text());
$(this).remove();
});
Js fiddle link added.
http://jsfiddle.net/bJ7zj/#update
Thanks in advance
The issue seems to be jQuery UI defaulting to today's date when it can't parse several dates.
If you wont use , in your dates or plan on updated jQuery UI very soon, you can use the following fixhack which adds dates = dates.split(',').pop(), allowing the parser to parse the last date in the list when showing the control. You can put this code any place after the jQuery UI reference
$.datepicker._setDateFromField= function (inst, noDefault)
{
if (inst.input.val() == inst.lastVal)
{
return;
}
var dateFormat = this._get(inst, 'dateFormat');
var dates = inst.lastVal = inst.input ? inst.input.val() : null;
dates = dates.split(',').pop()
var date, defaultDate;
date = defaultDate = this._getDefaultDate(inst);
var settings = this._getFormatConfig(inst);
try
{
date = this.parseDate(dateFormat, dates, settings) || defaultDate;
} catch (event)
{
this.log(event);
dates = (noDefault ? '' : dates);
}
inst.selectedDay = date.getDate();
inst.drawMonth = inst.selectedMonth = date.getMonth();
inst.drawYear = inst.selectedYear = date.getFullYear();
inst.currentDay = (dates ? date.getDate() : 0);
inst.currentMonth = (dates ? date.getMonth() : 0);
inst.currentYear = (dates ? date.getFullYear() : 0);
this._adjustInstDate(inst);
};

PhoneGap 2.0 (Cordova) DatePicker PlugIn 'mode'-Property to get Date AND Time

Today I started creating my first (Android-)App with PhoneGap, using the DatePicker-Plugin. After some hours of investigation I've got it to work (thanks to datePicker plugin not working in Phonegap 2.0) but not exactly I want:
I have an input with class="nativedatepicker" (date) (selector for the jQuery click-event) and one with class="nativetimepicker" (time) so I can choose in the first input the date and in the second the time.
Is it possible to merge this to one input where I can choose date and time in one step? I think I can do this somewhere here (some JS out of the PlugIn):
window.datePicker.show({
date : myNewDate,
mode : 'date', // date or time or blank for both
allowOldDates : true
}
but when I leave the mode blank it throws an error.
Thanks for your help!
How do you leave it blank exactly ?
If you do
mode : ,
You will get errors because the JS object needs a value for all keys you specify. You can try
mode : '',
No, currently that is not possible using the current DatePicker plugin for android, even though they say that if you set the mode property to blank you will get both. You can see it in DatePickerPlugin.java file:
if (ACTION_TIME.equalsIgnoreCase(action)) { //mode is set to "time"
//plugin java code
} else if (ACTION_DATE.equalsIgnoreCase(action)) { //mode is set to "date"
//plugin java code
} else { //mode is blank
Log.d(pluginName, "Unknown action. Only 'date' or 'time' are valid actions");
return;
}
My solution for the problem of selecting both date and time is to first show the date dialog and in the success callback show the time dialog.
The code looks like this:
var showDialog = function(mode, date, cb) {
window.plugins.datePicker.show({
date : date,
mode : mode
}, function(dateStr) {
cb(new Date(dateStr));
});
};
$('.nativedatepicker').click(function(e) {
e.preventDefault();
var currentField = $(this);
var oldDate = new Date(currentField.val()) || new Date();
//show the dialog to select the date
showDialog("date", oldDate, function(newDate) {
//we have a new date selected, copy time values from the old date for time dialog
newDate.setHours(oldDate.getHours());
newDate.setMinutes(oldDate.getMinutes());
//show the time dialog
showDialog("time", newDate, function(newDateTime) {
//now we have time selected, copy it to new date and update the field
newDate.setHours(newDateTime.getHours());
newDate.setMinutes(newDateTime.getMinutes());
currentField.val(newDate.toISOString());
});
});
return false;
});
Here is my alternative solution to DZL's answer. I have the date and time hooked up to two separate buttons that both alter the same date:
var date = new Date();
var $date = $('#date_result');
var normalizeNumber = function(n){
var c = parseInt(n, 10);
return (c<10) ? "0"+c : c;
}
var normalizeTime = function(t){
var hours = t.getHours();
var minutes = t.getMinutes();
var meridiem = ' AM ';
if (hours > 12) {
hours -= 12;
meridiem = ' PM ';
} else if (hours === 0) {
hours = 12;
}
minutes = normalizeNumber(minutes);
return hours + ':' + minutes + meridiem;
}
$('#date-btn').on('click', function(event) {
var myNewDate = date;
if(typeof myNewDate === "number"){ myNewDate = new Date (myNewDate); }
window.plugins.datePicker.show({
date : myNewDate,
mode : 'date',
allowOldDates : true
}, function(returnDate) {
var newDate = new Date(returnDate);
newDate.setMinutes(date.getMinutes());
newDate.setHours(date.getHours());
date = newDate;
$date.val(newDate.toLocaleDateString() + ' ' + normalizeTime(newDate));
$date.blur();
});
});
$('#time-btn').on('click', function(event) {
var myNewTime = date;
if(typeof myNewTime === "number"){ myNewTime = new Date (myNewTime); }
plugins.datePicker.show({
date : myNewTime,
mode : 'time',
allowOldDates : true
}, function(returnDate) {
var newDate = new Date(returnDate);
newDate.setDate(date.getDate());
newDate.setMonth(date.getMonth());
newDate.setFullYear(date.getFullYear());
date = newDate;
$date.val(newDate.toLocaleDateString() + ' ' + normalizeTime(newDate));
$date.blur();
});
});

Categories