Increase or decrease value using jquery - javascript

I have a javascript variable which is the day number of current date.
I wanted to give the user to go to previous date by clicking on a button.
Here's the fiddle.
Tried googling but I didn't understand or anything did help me.
I'm able to decrease just one day by giving -1 in the day variable. But I couldn't figure out how to decrease it on each click.
Someone help me in how can I decrease and increase the date of click of those buttons?
Thanks in advance.

There are a couple of problems in your code. The major one being that you create a new date Object on every button click with the current date. That's why you're getting the same result every time.
If you just want to add or remove one day from the date you could do just this:
var currentDate = new Date();
$('button').click(function() {
var add = $(this).hasClass('increase_date') ? 1 : -1;
currentDate.setDate(currentDate.getDate()+add);
$('.display_date').html(currentDate);
})
http://jsfiddle.net/3VQZy/

Store your current date in a global variable & use -= operator on it do decrese it by one using current value.
Something like this http://jsfiddle.net/SYRDR/2/
I only show how to decrease it, you have to add further conditions to formatt date properly

demo: http://jsfiddle.net/SYRDR/14/
$(document).ready(function() {
showDate(0);
$('.decrease_date').click(function() {
showDate(-1);
});
$('.increase_date').click(function() {
showDate(1);
});
})
function showDate(change)
{
var current_date;
if(change == 0)
{
current_date = new Date();
}
else
{
current_date = new Date($('.display_date').html());
}
var year = current_date.getFullYear();
var month = "0" + (current_date.getMonth() + 1);
var day = current_date.getDate();
if(change == -1)
{
day = day - 1;
}
if(change == 1)
{
day = day + 1;
}
var start_date2 = year + "-" + month + "-" + day;
$('.display_date').html(start_date2);
}

Related

How to convert user timezone to UTC?

I'm using the TimeIt code on my site, it can be found here: http://codegen.in/timeit/
This is the direct link to the code: https://res.cloudinary.com/vsevolodts/raw/upload/v1503371762/timeit.min.js
It looks like this:
//version 3. 2017-08-13
function timeit() {
var next_run_array = []; //array of dates/time on a page used to rerun function if a change should happen during the session
var curDate = new Date();
Date.prototype.yyyymmdd = function() {
var mm = this.getMonth() + 1;
var dd = this.getDate();
return [this.getFullYear(),
(mm > 9 ? '' : '0') + mm,
(dd > 9 ? '' : '0') + dd
].join('-');
};
var curDateYMD = curDate.yyyymmdd();
$('.timeit').each(function() {
var end = $(this).data('end'),
start = $(this).data('start');
//check if date or time value has valid format and push it to the list of refresh anchors
var startDate = checkdate(start, this);
var endDate = checkdate(end, this);
nextrun(startDate);
nextrun(endDate);
//add a datetime when the page needs to be refreshed (now+24 hrs time span only)
function nextrun(date) {
var nextruntimeout = date - curDate;
if (nextruntimeout < 1000 * 60 * 60 * 24 && nextruntimeout > 1000) {
next_run_array.push(nextruntimeout);
}
}
// Main Function
//check if the evend outside of a desired time span
if (((startDate < endDate) && (startDate > curDate || endDate < curDate)) ||
((startDate > endDate) && (startDate >= curDate) && (endDate <= curDate))
) {
$(this).addClass('hidden');
} else {
$(this).removeClass('hidden');
}
//Support Functions
//correct data creation from a string. accepted format YYYY-MM-DD HH:MM
function parseISO8601(d) {
var isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)?.(\d\d)?.(\d\d)\s*$/,
date = new Date(NaN),
datenew,
month,
dateString=d.substr(0, d.indexOf(' '));
parts = isoExp.exec(d);
if(parts) {
month = +parts[2];
date.setFullYear(parts[1], month - 1, parts[3]);
if(month != date.getMonth() + 1) {
date.setTime(NaN);
}
date = new Date(parts[1], month - 1, parts[3], parts[4], parts[5])
}
return date;
}
//unification of the date string to the format YYYY-MM-DD HH:MM
function checkdate(date, obj) {
if (date) {
//check if only time is set (HH:MM); if so, add today's date
if (String(date).length < 6 && String(date).indexOf(":") > -1) {
date = curDateYMD + ' ' + String(date);
}
//check if only date is set; if so add 00:00 to the end of date
if (String(date).indexOf(":") == -1) {
date = date + ' 00:00';
}
//check if date is valid (avoid valid time)
var res = date.split(":"),
h = String(res.slice(0, 1)),
hours = h.substr(h.length - 2),
minutes = res.slice(1);
var timetest = (hours < 24 && minutes < 60) ? true : false;
//check if date is could be created from a value; if fails try to parse a string to a format
var returndate = new Date(date);
if (returndate == 'Invalid Date') {
var returndate = parseISO8601(date);
};
if (returndate == 'Invalid Date' || !timetest) {
//highlight the element if the is an error. use own \.error class if needed
$(obj).addClass("error").attr('title', '"' + date + '" date is incorrect; please use YYYY-MM-DD HH:MM format');
}
return returndate.getTime();
} else {
//if datetime is not set, just return current date-time
return curDate.getTime();
}
}
});
/* Schedule next runs */
if (next_run_array.length > 0) {
var nextruntime = Math.min.apply(null, next_run_array);
console.log("next run of timeit function is in " + nextruntime / 1000 + "seconds");
setTimeout(function() {
timeit();
}, nextruntime);
}
}
timeit();
(
Then you just put the embed code:
<div class="timeit" data-start="2019-02-15" data-end="2019-07-25 23:59">
This content will be shown between 2019-02-15 - 2019-07-25
</div>...<script src="/js/timeit.js"></script>
The idea is: my content is being shown between a certain period of time. I would like it to work with the UTC time zone, but right now the code is getting the date/hour info from the user's local time zone. So my content becomes available for example not at 8 AM UTC, but at 8 AM of the user's local time zone. I would like to change that.
I really, really tried to work this out on my own, but I guess this is beyond my skill set (which is pretty low). I'm confused by all the info about those ISO 8601, new Date, Date, I can't really find where it says "get the time from this source" to replace it with "get it from UTC". So - if any of you would just take a look at it and tell me what to put where, I would be extremely grateful.
Thank you all for your time!
Since you can't use server-side scripting because of Weebly... You will have to rely on the client's clock which can be tweeked. And the hidden class can easily be removed... But it seems you don't have the choice.
Now, I will suggest you to forget about the TimeIT plugin.
When it comes to dates in JavaScript/jQuery, I always recommand the use of moment.js which is really easy to use (you won't have to perform complex caluculations anymore) and fully documented, so you can do whatever you wish.
Here, content hiding based on start/end dates in data attributes would look like this:
$(document).ready(function(){
var utc_date = moment().utc().format("YYYY-MM-DD HH:mm"); // Client's date/time in UTC
$(".timeit").each(function(){
var start = moment($(this).data("start")).format("YYYY-MM-DD HH:mm");
var end = moment($(this).data("end")).format("YYYY-MM-DD HH:mm");
console.log((utc_date>start && utc_date<end)?"Content displayed":"Content hidden");
$(this).addClass("hidden"); // Hide content by default
if(utc_date>start && utc_date<end){
$(this).removeClass("hidden"); // Show content if now is between start/end dates
}
});
}); // ready
.hidden{
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<div class="timeit" data-start="2019-02-15" data-end="2019-07-25 23:59">
This content will be shown between the dates in data attributes
</div>
You can try it in CodePen... Change the start date and hit "Run". I left some console logs so you can understand what is going on.
For more, explore moment.js documentation.

check if "current time" is between 2 times. But also check for nights as the day before

I have 2 times for example: 10:00 and 1:00 now i want to check if current time... is between these 2 times in javascript.
The problem is that the closing time in this case is a next day so its before the openingstime. How can i do this the proper way for some reason i can not get around this.
i hav efound that this could solve it:
var start = new Date(2012,6,20,13).getTime();
var now = new Date().getTime();
var end = new Date(2012,6,21,2).getTime();
if( (start < now ) && (now < end )) {
console.log("opened");
}
else {
console.log("closed");
}
but how can i do it with 2 string formats like 10:00 and 2:00 because i do not see a option to put a time alone
var d = new Date();
var d = new Date(milliseconds);
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
You could use a simple function like this to convert your time to a number of minutes since 0:00:
function getMinutes(str) {
var time = str.split(':');
return time[0]*60+time[1]*1;
}
And a similar function to get the current time into the same form in order to compare:
function getMinutesNow() {
var timeNow = new Date();
return timeNow.getHours()*60+timeNow.getMinutes();
}
Then convert both opening and closing time and, if it happens that closing time is before opening time, add 24 hours to it.
var now = getMinutesNow();
var start = getMinutes('10:00');
var end = getMinutes('2:00');
if (start > end) end += getMinutes('24:00');
if ((now > start) && (now < end)) { // your code here
This is the solution I've gotten to after a bit of fiddling. At the current time of 3:24 am, it outputs the correct information. changing the now array to be [13,00] also gave the correct result of 'closed' Give it a test run through to make sure it works correctly.
Edit
jQuery included solely because I am brain dead.
Edit#2
I noticed now (9pm my time) that my conversion wasn't working, it was saying 'closed', when it shouldn't have. So far, this works for any and all numbers I've put in it to test.
var start_time = [20,00]
var end_time = [12,00]
//We've got the two start times as an array of hours/minutes values.
var dateObj = new Date(); //I just feel dirty making multiple calls to new Date().etc
var now = [dateObj.getHours(),dateObj.getMinutes()]; //Gets the current Hours/Minutes
if(end_time[0] < start_time[0] && now[0] < start_time[0]){
start_time[0] -= 24; //This is something I came up with because I do a lot of math.
}else if(start_time[0] > end_time[0]){
end_time[0]+=24;
}
var el=$('#result');
var start_string = to_hms_string(start_time); //the start string converted to a string format. Made comparisons easier.
var end_string = to_hms_string(end_time); //See Above
var now_string = to_hms_string(now); //Above
console.log(start_string, now_string, end_string);
var status = (start_string < now_string && now_string < end_string) ? "Open" : "Closed";
el.html(status);
//Function to_hms_string stands for "hour-minute-second" string. First name that came up.
function to_hms_string(timearr){
var minutes = 60+timearr[1];
var hours = "";
if(Math.abs(timearr[0]) < 10){
hours = "0";
}
hours = (timearr[0]<0) ? "-"+hours+Math.abs(timearr[0]) : hours+timearr[0];
return hours+":"+minutes;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result">
PlaceHolder
</div>
You can do this, get current time. Then define you start time and end time based on the current time getting the year, month, date for tomorrow's date add 1 to the start's date see code below. Then you can compare the time the same fi condition you have. Good luck
var now = new Date();
var start = new Date(now.getFullYear(),now.getMonth(),now.getDate(),7).getTime();
var end = new Date(now.getFullYear(),now.getMonth(),now.getDate() + 1,2).getTime();
now = now.getTime();
if( now >= start && now < end) {
console.log("opened");
}
else {
console.log("closed");
}
***EDIT**
You can convert the current time to millis after you get the year, month and date. Then use your current if condition.
Jhecht This thing right here:
if(end_time[0] < start_time[0] && now[0] < start_time[0]){
start_time[0] -= 24;
}else if(start_time[0] > end_time[0]){
end_time[0]+=24;
}
it's brilliant. It works and this is the correct answer. Great job!

previous quarters in javascript

Forgive me I tried several searches here and other places in general but cant seem to fix issue I am having at the moment. Can someone please help me figure out?
I am trying to find quarter strings from inputdate in JavaScript. For "01/31/2009" it should give Q1,2013 Q4,2012 etc based on offset given as input parameter. when offset is 0 then current quarter, 1 then previous, 2 then previous 2 quarter etc...
my current code: jsfiddle
function getQuarterStrings(id) {
var d = new Date();
var d = new Date("01/31/2009");
var str;
switch (id) {
...
}
Remaining code is in jsfiddle. As you can see, it fails on second last condition even though everything seems ok. Please help me figure out my mistake. Thank you!
Some of your comparisons are off, and Date tries to compensate for months that don't have as many days when you setMonth. This code should work:
function getQuarterStrings(id) {
var d = new Date("03/31/2009");
d.setDate(1);
d.setMonth(d.getMonth() - id * 3);
var month = d.getMonth() + 1;
var year = d.getFullYear();
var quarter = Math.ceil(month / 3);
return ("Q" + quarter + ", " + year);
}
This works, and is a lot more concise. It also allows you to use any offset instead of a limited set of values:
function getQuarterStrings(date, id) {
// quarter is 0-based here
var quarter = Math.floor(date.getMonth() / 3),
year = date.getFullYear();
quarter -= id;
if(quarter < 0) {
var yearsChanged = Math.ceil(-quarter / 4);
year -= yearsChanged;
// Shift quarter back to a nonnegative number
quarter += 4 * yearsChanged;
}
return "Q" + (quarter + 1) + ", " + year;
}
http://jsfiddle.net/dPmf2/6/
You can also get rid of the switch statement by doing this:
function getQuarterStrings(id) {
var d = new Date();
var d = new Date("01/31/2009");
var str;
if (id !== 0){
d.setMonth(d.getMonth() - 3*id);
}
str = getQuarter(d);
return str;
}

Date Validation in javascript?

i have problem with date validation in javascript
the problem is i have popup calendar the return a date value
i want to check the date in javascript before send it to parent page
in popup calendar.aspx
function passDateValue(DateValue)
{
window.returnValue=DateValue;
window.close();
return false;
}
in popup calendar codebehind
ClientScript.RegisterStartupScript(GetType(), "SelectDate", "passDateValue('" + clrPopUp.SelectedDate.ToShortDateString() + "')", true);
the function that call the popup calendar and check the returned value
function Calendar_popup(tbClientID)
{
var today = new Date();
var Day = today.getDate();
var Month = today.getMonth()+1;
var Year = today.getFullYear();
if(Month<10){Month = '0'+Month;}
if(Day<10){Day = '0'+Day;}
var todayFormat = Day + "/" + Month + "/" + Year;
datevalue = window.showModalDialog("Calendar_Dialog.aspx?ctlid=" + tbClientID, '',"dialogHeight:250px;dialogWidth:300px;");
var startdate = Date.parse(datevalue);
var enddate = Date.parse(todayFormat);
if (startdate>enddate)
{alert('BirthDate Must be less than today');
return;
}
}
is there anyway to check date ?
thanks!
Check out date.js, specifically...
http://code.google.com/p/datejs/wiki/APIDocumentation#compare
Compares the first date to the second date and returns an number
indication of their relative values. -1 = this is < date. 0 =
values are equal. 1 = this is > date.
The isAfter() and the isBefore() methods might be useful for your problem :)
Download the library here:
http://code.google.com/p/datejs/downloads/detail?name=date.js&can=2&q=

Get next date and day

I have a table to which i dynamically add rows. The number of days is equal to the date difference of the dates inserted by user. On the dynamic rows i want to add three fields. The first two are date and day filed. For that I need to know the next date and the corresponding day. For example user enters 10-2-2012. I need to insert The next dates like 17-2-2012,18-2-2012... and corresponding days like Wednesday, Thursday..etc
I have used the following function to get next date
function getTomorrow(d,offset)
{
if (!offset)
{
offset = 1
}
return new Date(new Date().setDate(d.getDate() + offset));
}
But it shows error 16-2-2012 has no getDate() function. Am not able to find next date and the corresponding day. Is there any way to get it?
You have to convert the string d into a Date object:
function getTomorrow(d,offset){
if (!offset){
offset = 1;
}
if(typeof(d) === "string"){
var t = d.split("-"); /* splits dd-mm-year */
d = new Date(t[2],t[1] - 1, t[0]);
// d = new Date(t[2],t[1] - 1, t[0] + 2000); /* for dd-mm-yy */
}
return new Date(d.setDate(d.getDate() + offset));
}
document.write(getTomorrow('16-02-2012',20) + ' test');
var k = getTomorrow('16-02-2012',1);
var myTime = k.getDate()+'-'+(k.getMonth()+1)+'-'+k.getFullYear();
alert(myTime);
JSFiddle Demo. See also http://www.w3schools.com/jsref/jsref_obj_date.asp.
var d=new Date();
d.setTime((d.getTime() + 86400 * 1000*1));
document.write(d);
document.write(d.getDay()+"-"+parseInt(d.getMonth()+1)+"-"+d.getFullYear());
if you need to know the date of day after tommorow , just change 1000*1 to 1000*2.
i giving a example
var year = 2010, month = 9, day = 14;
// The value of `meses`
var offset = 1; // Tomorow
var future_date = new Date(year, month , day+offset);
console.log(future_date);

Categories

Resources