How to sum days to some date - javascript

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!

Related

How can set the filename to today's date? window.saveAs(blob, 'Time');

How can set the filename to today's date?
$("#download").on("click", function() {
html2canvas(document.querySelector("#to_save")).then(canvas => {
canvas.toBlob(function(blob) {
window.saveAs(blob, #);
});
});
});
I couldn't find a solution.
What format did you want the time in?
If you want YYYY-MM-DD, you can use toLocaleDateString set the locale to Swedish (Sweden) i.e. sv-SE. For more information on date formatting, see Intl.DateTimeFormat.
(function($) {
$.todaysDate = function() {
return new Date().toLocaleDateString('sv-SE');
};
})(jQuery);
$("#download").on("click", function() {
html2canvas(document.querySelector("#to_save")).then(canvas => {
canvas.toBlob(function(blob) {
window.saveAs(blob, $.todaysDate());
});
});
});
console.log($.todaysDate()); // Today's date in YYYY-MM-DD
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Here are all the locales for comparison:
const now = new Date();
const datesByLocale = {
'ar-SA': now.toLocaleDateString('ar-SA'),
'bn-BD': now.toLocaleDateString('bn-BD'),
'bn-IN': now.toLocaleDateString('bn-IN'),
'cs-CZ': now.toLocaleDateString('cs-CZ'),
'da-DK': now.toLocaleDateString('da-DK'),
'de-AT': now.toLocaleDateString('de-AT'),
'de-CH': now.toLocaleDateString('de-CH'),
'de-DE': now.toLocaleDateString('de-DE'),
'el-GR': now.toLocaleDateString('el-GR'),
'en-AU': now.toLocaleDateString('en-AU'),
'en-CA': now.toLocaleDateString('en-CA'),
'en-GB': now.toLocaleDateString('en-GB'),
'en-IE': now.toLocaleDateString('en-IE'),
'en-IN': now.toLocaleDateString('en-IN'),
'en-NZ': now.toLocaleDateString('en-NZ'),
'en-US': now.toLocaleDateString('en-US'),
'en-ZA': now.toLocaleDateString('en-ZA'),
'es-AR': now.toLocaleDateString('es-AR'),
'es-CL': now.toLocaleDateString('es-CL'),
'es-CO': now.toLocaleDateString('es-CO'),
'es-ES': now.toLocaleDateString('es-ES'),
'es-MX': now.toLocaleDateString('es-MX'),
'es-US': now.toLocaleDateString('es-US'),
'fi-FI': now.toLocaleDateString('fi-FI'),
'fr-BE': now.toLocaleDateString('fr-BE'),
'fr-CA': now.toLocaleDateString('fr-CA'),
'fr-CH': now.toLocaleDateString('fr-CH'),
'fr-FR': now.toLocaleDateString('fr-FR'),
'he-IL': now.toLocaleDateString('he-IL'),
'hi-IN': now.toLocaleDateString('hi-IN'),
'hu-HU': now.toLocaleDateString('hu-HU'),
'id-ID': now.toLocaleDateString('id-ID'),
'it-CH': now.toLocaleDateString('it-CH'),
'it-IT': now.toLocaleDateString('it-IT'),
'ja-JP': now.toLocaleDateString('ja-JP'),
'ko-KR': now.toLocaleDateString('ko-KR'),
'nl-BE': now.toLocaleDateString('nl-BE'),
'nl-NL': now.toLocaleDateString('nl-NL'),
'no-NO': now.toLocaleDateString('no-NO'),
'pl-PL': now.toLocaleDateString('pl-PL'),
'pt-BR': now.toLocaleDateString('pt-BR'),
'pt-PT': now.toLocaleDateString('pt-PT'),
'ro-RO': now.toLocaleDateString('ro-RO'),
'ru-RU': now.toLocaleDateString('ru-RU'),
'sk-SK': now.toLocaleDateString('sk-SK'),
'sv-SE': now.toLocaleDateString('sv-SE'),
'ta-IN': now.toLocaleDateString('ta-IN'),
'ta-LK': now.toLocaleDateString('ta-LK'),
'th-TH': now.toLocaleDateString('th-TH'),
'tr-TR': now.toLocaleDateString('tr-TR'),
'zh-CN': now.toLocaleDateString('zh-CN'),
'zh-HK': now.toLocaleDateString('zh-HK'),
'zh-TW': now.toLocaleDateString('zh-TW'),
};
const formatToLocales = _.invertBy(datesByLocale);
console.log(formatToLocales);
.as-console-wrapper { top: 0; max-height: 100% !important; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
From the example above, we can see that the following locales provide the YYYY-MM-DD date format:
en-CA ~ English (Canada)
fr-CA ~ French (Canada)
sv-SE ~ Swedish (Sweden)
See also: http://www.lingoes.net/en/translator/langcode.htm
I found the solution
$( "#download" ).on( "click", function() {
html2canvas(document.querySelector("#to_save")).then(canvas => {
canvas.toBlob(function(blob) {
window.saveAs(blob, getFormattedTime());
function getFormattedTime() {
var today = new Date();
var y = today.getFullYear();
// JavaScript months are 0-based.
var m = today.getMonth() + 1;
var d = today.getDate();
return y + "-" + m + "-" + d;
}
});
});
});

Check if a HTML has loaded into a DIV

I want to be able to set up HTML pages and load them into a single home page. Each html file will be named as the date (eg 03052016.html for today) and then the correct html will be pulled in each day on the homepage.
However not all days will have a html file, in which case it should roll back to a previous day. I have successfully loaded the page, nice and easy but can't work out a way to identify that the page hasn't loaded and subtract one from the day. My current attempt is the following:
<body>
<div id="success"></div>
<script>
//section creates the html file name for today
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10) {
dd='0'+dd
}
if(mm<10) {
mm='0'+mm
}
today = dd+mm+yyyy+'.html';
var today = "05052016.html";
//do loop to subtract days until file is found
do{
var found = true; //variable records file presence
$( "#success" ).load( today, function( response, status, xhr ) {
if ( status == "error" ) {
var found = false;
if(parseInt(dd)>1){
dd = parseInt(dd)-1;
}else {
mm = parseInt(mm)-1;
dd = 30 //will deal with 31/30/28 day months later.
}
if(dd<10) {
dd='0'+dd
}
if(mm<10) {
mm='0'+mm
}
today = dd+mm+yyyy+'.html';
//
console.log( msg + xhr.status + " " + xhr.statusText );
}
});
}until(found == false )
</script>
I am new to web authoring so please be brutal if I am way off how to implement this. It seems so easy but the loop just won't work!
I am currently testing in FireFox, and using jquery-1.10.2.js
check de length of the content of the quuestioned div.
var div = $('div');
var dHtml = div.html();
var long = dHtml.length;
if(long > 0)
{
//do stuff
}
You need to understand that ajax (which is behind load) is asynchronous so you cannot test the found outside the success.
Try this:
function pad(num) {return String("0"+num).slice(-2)}
function getFilename(date)
var dd = pad(date.getDate());
var mm = pad(date.getMonth()+1); //January is 0!
var yyyy = date.getFullYear();
return ""+dd+mm+yyyy+".html";
}
var date = new Date(),
aDay = 10*24*60*60*1000,
giveUp = new Date(date.getTime()-(10*aDay)); // max 10 days back
function loadFile(date) {
$("#success").load( getFilename(date), function() {
if (status == "error") {
if (date>giveUp) {
date.setDate(date.getDate()-1)
loadFile(date);
}
}
});
}
$(function() {
loadFile(date);
});

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);
};

Apply different attribute to each element of same class

What do I need to change in my code?
Each element with the class "date_entry" should have a different attribute set, but currently all elements with that class are getting the same attribute...
$("document").ready(function() {
$(".date_entry").each(function() {
if ($(".date_entry").attr("date", "")) {
var date = $(this).text();
var splitDate = date.split('/');
var year = splitDate[2];
var month = splitDate[0];
var day = splitDate[1];
var newAttr = year + month + day;
$(".date_entry").attr("date", newAttr);
}
});
});​
Use the "this" variable:
$(function() {
$(".date_entry").each(function() {
var date = $(this).text();
var splitDate = date.split('/');
var year = splitDate[2];
var month = splitDate[0];
var day = splitDate[1];
var newAttr = year + month + day;
$(this).attr("date", newAttr);
});
});
You have to use $(this) instead of $(".date_entry") inside the function you are passing to each(). $(".date_entry") selects again all elements with that class.

Date formatting options using 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.

Categories