Supposedly, I should be able to create an arbitrary date using the Date constructor as demonstrated here and referenced here
Where am I going wrong? Please notice that on the last few lines of prettyDateToTimeStamp, I modify the month and day to verify that the Date constructor is doing something - but it is not noticing anything I pass in and just returns the current date.
Here is my code below: and a jsfiddle
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to display the full year of todays date.</p>
<p id="demo2">todays date.</p>
<p id="demo3">some other date.</p>
<button onclick="showdates()">Try it</button>
<script>
function showdates() {
var d = Date.now();
var dv = document.getElementById('demo');
dv.innerHTML = d;
var pd = prettyDate(d);
dv = document.getElementById('demo2');
dv.innerHTML = pd;
var ts = prettyDateToTimeStamp(pd);
dv = document.getElementById('demo3');
dv.innerHTML = ts;
}
function prettyDate(javaScriptTimeStamp) {
var dt = new Date(javaScriptTimeStamp);
var year = dt.getFullYear();
var month = dt.getMonth() + 1;
var day = dt.getDate();
var hours = dt.getHours();
var minutes = dt.getMinutes();
var seconds = dt.getSeconds();
return month + "/" + day + "/" + year + " " + hours + ":" + minutes + ":" + seconds;
}
function prettyDateToTimeStamp(prettyDate) {
var halves = prettyDate.split(' ');
console.log("halves: " + halves);
var calpart = halves[0];
console.log("calpart : " + calpart );
var clockpart = halves[1];
console.log("clockpart : " + clockpart );
var calbits = calpart.split('/');
console.log("calbits : " + calbits );
var timebits = clockpart.split(':');
console.log("timebits : " + timebits );
var year = parseInt(calbits[2],10);
console.log("year : " + year );
var month = parseInt(calbits[0],10);
console.log("month : " + month );
var day = parseInt(calbits[1],10);
console.log("day : " + day );
var hour = parseInt(timebits[0],10);
console.log("hour : " + hour );
var min = parseInt(timebits[1],10);
console.log("min : " + min );
var sec = parseInt(timebits[2],10);
console.log("sec : " + sec );
month += 3; // change month radically to demonstrate the problem
console.log("month is now: " + month );
day += 7; // change day too
console.log("day is now: " + day );
var ts = Date(year,month,day,hour,min,sec,0);
console.log("ts : " + ts ); // date ctor paramters completely ignored...?
return ts;
}
</script>
</body>
</html>
omg, I have to say "new" Date .... (I've been using Python too much lately)
corrected code now works.
function prettyDateToTimeStamp(prettyDate) {
var halves = prettyDate.split(' ');
var calpart = halves[0];
var clockpart = halves[1];
var calbits = calpart.split('/');
var timebits = clockpart.split(':');
var year = parseInt(calbits[2],10);
var month = parseInt(calbits[0],10);
var day = parseInt(calbits[1],10);
var hour = parseInt(timebits[0],10);
var min = parseInt(timebits[1],10);
var sec = parseInt(timebits[2],10);
month += 3; // change month radically to demonstrate the problem
day += 7; // change day too
var ts = new Date(year,month,day,hour,min,sec,0); // you have to use NEW here!
return ts;
}
Related
I'm trying to separate concerns using modules in Js eveything is going Ok except that I want to display the time of the system and I did that too but when I output it I got an [object Object] string and what proves me right that really I got the right system Time is that when I console logged the interCtrl.getTheTime I got the time of the system and here is a screenshot:
here is my code to let you understand better:
JS:
var controller = (function(interCtrl, UICtrl) {
//1.get the time
setInterval(document.querySelector(".Time").innerHTML = interCtrl.getTime(),100);
// console.log(interCtrl.getTime());
//2.get the date
document.querySelector(".subDate").innerHTML = interCtrl.date();
};
document.querySelector(".add__btn").addEventListener("click", ctrlAddPlans);
document.addEventListener("keypress", function(e) {
if (e.keyCode === 13) {
ctrlAddPlans();
}
});
})(internalController);
var internalController = (function() {
//some code
function getTheDate() {
var newDate;
var d = new Date();
var day = d.getDate();
var year = d.getFullYear();
var month = d.getMonth() + 1;
// var x=1;
if (month.toString().length < 2) {
month = " 0" + month + " ";
}
var date = " %11%/%04%/%2019%";
newDate = date.replace("%11%", day + " ");
newDate = newDate.replace("%04%", month);
newDate = newDate.replace("%2019%", " " + year);
return newDate;
}
function getTheTime() {
//.get the timeDiv
// const timeDiv =
//.get the time (h,m,s)
var date = new Date();
var hours = date.getHours();
if (hours.toString().length < 2) {
hours = `0${hours}`;
}
var mins = date.getMinutes();
if (mins.toString().length < 2) {
mins = `0${mins}`;
}
var seconds = date.getSeconds();
return {
time: hours+ " : "+ mins+" : "+seconds
};
}
return {
date: function getDate() {
return getTheDate();
},
getTime: function getTime() {
return getTheTime();
}
};
})();
I saw this question but it didn't help me what does [object Object] mean?
so any help please and thank you in advance
The output of the getTime function is an object. To make it output a string, you can change its return statement from
return {
time: hours+ " : "+ mins+" : "+seconds
};
to
return hours + " : " + mins+" : " + seconds;
Or, alternatively, if you want it to be an object, you'll have to access its time property to get the value. Like
var timeObj = interCtrl.getTheTime();
var timeString = timeObj.time;
Hello I am trying to add increment in my all form fields from zero to the number whenever I add new clone it assigns the next number to the name tag, I tried all the ways but no any methods works for me.
Here is my fiddle
https://jsfiddle.net/o5wam5r2/
and here is my JS code
var formItem;
$(document).ready(function() {
//Clone and remove your div instead of hiding it
formItem = $('.ScheduleextraPartTemplate').clone();
$('.ScheduleextraPartTemplate').remove();
formItem.addClass('clone clone-1');
$('#Schedulecontainer').append(formItem);
});
$(document).on('click', '#ScheduleaddRow', function() {
var cloneForm = $('.clone').last().clone();
var cloneNum = $('.clone').length;
cloneForm.removeClass('clone-'+cloneNum).addClass('clone-' + (cloneNum+1));
var date = cloneForm.find('[name="txtSchedule"]').val();
cloneForm.find('[name="txtSchedule"]').val(addOneMonth(date));
$('#Schedulecontainer').append(cloneForm);
})
function addOneMonth(date) {
var year = parseInt(date.split("-")[0]);
var month = parseInt(date.split("-")[1]) + 1;
var day = parseInt(date.split("-")[2]);
if(month > 12) {
month = month - 12;
year++
}
return year + "-" + month + "-" + day;
}
I fixed it by changing a little piece of code
var formItem;
var counter = 0;
$(document).ready(function() {
//Clone and remove your div instead of hiding it
formItem = $('.ScheduleextraPartTemplate').clone();
formItem.find('[name^=txtSchedule]')[0].name = "txtSchedule" + counter;
formItem.find('[name^=txtScheduleAmountPay]')[0].name = "txtScheduleAmountPay" + counter;
$('.ScheduleextraPartTemplate').remove();
formItem.addClass('clone clone-1');
$('#Schedulecontainer').append(formItem);
});
$(document).on('click', '#ScheduleaddRow', function() {
var lens = counter++;
var cloneForm = $('.clone').last().clone();
var cloneNum = $('.clone').length;
cloneForm.removeClass('clone-'+cloneNum).addClass('clone-' + (cloneNum+1));
var date = cloneForm.find('[name^="txtSchedule"]').val();
cloneForm.find('[name^="txtSchedule"]').val(addOneMonth(date));
cloneForm.find('[name^=txtSchedule]')[0].name = "txtSchedule" + (lens+1);
cloneForm.find('[name^=txtScheduleAmountPay]')[0].name = "txtScheduleAmountPay" + (lens+1);
$('#Schedulecontainer').append(cloneForm);
})
function addOneMonth(date) {
var d = new Date( date );
d.setMonth( d.getMonth( ) + 1 );
return d.getFullYear() + '-' + ("0" + ((d.getMonth() + 1))).slice(-2) + '-' + ("0" + (d.getDate())).slice(-2);
}
Here is my code,
function getDateonperiod(elem)
{
var periodval=$("#period"+elem).val();
var days = periodval * 30;
var startDate=new Date();
var endDate = new Date();
endDate.setDate(endDate.getDate() + days);
var strDate = startDate.getFullYear() + "-" + (startDate.getMonth()+1) + "-" + startDate.getDate();
$("#from_date"+elem).val(strDate);
$("#to_date"+elem).val((endDate.getFullYear()+'-'+endDate.getMonth() + 1)+'-'+endDate.getDate());
}
Onchange input field value getting number of days days. I'm getting start date correctly but end date if input value 1 its working fine but its more than one its returning like this 2016-11-27 2016-21-28 from current date. How to fix this?
You missed a parenthesis:
endDate.getFullYear()+'-'+(endDate.getMonth() + 1)+'-'+endDate.getDate();
Try this:
$( "#period" ).change(function() {
var periodval=$("#period").val();
var days = periodval * 30;
var startDate=new Date();
var endDate = new Date();
endDate.setDate(endDate.getDate() + days);
var strDate = startDate.getFullYear() + "-" + (startDate.getMonth()+1) + "-" + startDate.getDate();
$("#from_date").val(strDate);
$("#to_date").val(endDate.getFullYear()+'-'+(endDate.getMonth() + 1)+'-'+endDate.getDate());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="period" />
<input type="text" id="from_date" />
<input type="text" id="to_date" />
you can use moment.js here
var days = 10;
var dateFormat = 'YYYY-MM-DD';
var startFormatted = moment().format(dateFormat);
var endFormatted = moment().add(days, 'day').format(dateFormat);
console.log(startFormatted)
console.log(endFormatted)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
You are not adding days correctly.
function getDateonperiod(elem)
{
var periodval=$("#period"+elem).val();
var days = periodval * 30;
var startDate=new Date();
var endDate = new Date(startDate.getFullYear(),startDate.getMonth(),startDate.getDate()+n);
var strDate = startDate.getFullYear() + "-" + (startDate.getMonth()+1) + "-" + startDate.getDate();
$("#from_date"+elem).val(strDate);
$("#to_date"+elem).val((endDate.getFullYear()+'-'+endDate.getMonth() + 1)+'-'+endDate.getDate());
}
Simply use this library
http://momentjs.com/
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js">
Your code with momentjs
function getDateonperiod(elem)
{
var periodval=$("#period"+elem).val();
var days = periodval * 30;
var startDate = new moment();
var endDate = new moment();
endDate.add(days,'days');
var strStartDate = startDate.format("YYYY - MM - DD");
var strEndDate = endDate.format("YYYY - MM - DD");
$("#from_date"+elem).val(strDate);
$("#to_date"+elem).val(strEndDate);
}
I just extended Date function for adding days. This may help you:
Date.prototype.addDays = function(days) {
this.setDate(this.getDate() + parseInt(days));
return this;
};
$("#period").change(function() {
var periodval = $("#period").val();
var days = periodval;
var startDate = new Date();
var endDate = new Date();
endDate.addDays(days);
//endDate.setDate(endDate.getDate() + days);
var strDate = startDate.getFullYear() + "-" + (startDate.getMonth() + 1) + "-" + startDate.getDate();
$("#from_date").val(strDate);
$("#to_date").val(endDate.getFullYear() + '-' + (endDate.getMonth() + 1) + '-' + endDate.getDate());
});
I have a script which lists Google Calendar events with the start time, name and description but I would like to have the end time too so it reads;
5:00pm - 6:00pm - Event title - event description
Rather than just what it has at the moment which is just the start time and not the end time.
This is the script I have:
$(document).ready(GCalEvents());
function GCalEvents() {
var datenow = new Date();
var curyear = datenow.getFullYear();
var curmonth = datenow.getMonth() + 1;
var curdate = datenow.getDate();
var curhour = datenow.getHours();
var curmin = datenow.getMinutes();
var curtz = datenow.getTimezoneOffset();
//curtz = -480;
var plusmin = "-";
if (curtz <= 0) {
plusmin = "%2B";
}
curtz = Math.abs(curtz);
var curtzmin = curtz % 60;
curtz = parseInt(curtz / 60);
if (curtzmin < 10) { curtzmin = "0" + curtzmin; }
if (curtz < 10) { curtz = "0" + curtz; }
datenow = curyear + "-" + curmonth + "-" + curdate + "T" + curhour + "%3A" + curmin + "%3A00" + plusmin + curtz + "%3A" + curtzmin;
var url = "https://www.googleapis.com/calendar/v3/calendars/{calendarid}/events?alwaysIncludeEmail=false&maxResults=2&orderBy=startTime&showDeleted=false&showHiddenInvitations=false&singleEvents=true&timeMin=" + datenow + "&fields=items(start%2Csummary%2Cdescription)%2CtimeZone&key={key}";
// var url = "https://www.googleapis.com/calendar/v3/calendars/{calendarid}/events?alwaysIncludeEmail=false&maxResults=2&orderBy=startTime&showDeleted=false&showHiddenInvitations=false&singleEvents=true&timeMin=" + datenow + "&fields=items(start%2Csummary%2Cdescription)%2CtimeZone&key={key}";
$.getJSON(url, function(data) {
var event_start_date_new = new Date();
event_start_date_new.setDate(event_start_date_new.getDate() - 1);
for(i in data['items']) {
item = data['items'][i];
// event title
var event_title = item.summary;
var event_description = item.description;
// event start date/time
var event_start_date = new Date(item.start.dateTime);
// format the date and time
var month = event_start_date.getMonth();
var day = event_start_date.getDay();
var date = event_start_date.getDate();
var daysArr = new Array();
daysArr[0] = "Sunday";
daysArr[1] = "Monday";
daysArr[2] = "Tuesday";
daysArr[3] = "Wednesday";
daysArr[4] = "Thursday";
daysArr[5] = "Friday";
daysArr[6] = "Saturday";
var monthsArr = new Array();
monthsArr[0] = "January";
monthsArr[1] = "February";
monthsArr[2] = "March";
monthsArr[3] = "April";
monthsArr[4] = "May";
monthsArr[5] = "June";
monthsArr[6] = "July";
monthsArr[7] = "August";
monthsArr[8] = "September";
monthsArr[9] = "October";
monthsArr[10] = "November";
monthsArr[11] = "December";
var hour = event_start_date.getHours();
var min = event_start_date.getMinutes();
if (min < 10) { min = "0" + min; }
if (hour < 11) {
var ampm = "am";
if (hour == 0) { hour = 12; }
} else {
var ampm = "pm";
if (hour > 12) { hour = hour - 12; }
}
if (hour < 10) { hour = " " + hour; }
var event_start_str = daysArr[day] + ", " + monthsArr[month] + " " + date;
var event_time_str = hour + ":" + min + " " + ampm;
if (event_start_date.getDate() != event_start_date_new.getDate()) {
event_start_str = "<div class=\"calendar_date\"><strong>" + event_start_str + "</strong></div>";
event_start_date_new = event_start_date;
} else {
event_start_str = "";
};
// Render the event
$("#gcal-events").last().before("<div class=\"calendar_item\"><li>" + event_time_str + " - " + event_title + "<p><small>" + event_description + "</small></p></ul>" + "</li></div>");
}
});
};
If anyone is able to help with that to reversion the current script, that would be great.
The Events resource returns start and end dates as well (JSON format that has date, dateTime, timeZone attributes).
Based on your code, you're not using the end attribute which is why you're not having any values for the end date displayed. Your code for the start date is alright, so you can just re-implement it for the end attribute.
Hope this helps!
How to check time conditionin Jquery
var startTime="20:02:55"; // or 12:34
var endTime ="21:02:55" // or 1:34
var dt = new Date();
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
if(time >startTime || time < endTiime){
$("#a").html("show Box");
}else{
$("#a").html("Expire BOx");
}
How to check 12 hour and 24 hour condition also?
is it correct? i need am, pm format check please can anyone help me?
Here is some code. I am appending to show both behaviour.
Here is DEMO
test("20:02:55", "21:02:55");
test("13:02:55", "15:02:55");
function test(start_time, end_time) {
var dt = new Date();
//convert both time into timestamp
var stt = new Date((dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear() + " " + start_time);
stt = stt.getTime();
var endt = new Date((dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear() + " " + end_time);
endt = endt.getTime();
var time = dt.getTime();
if (time > stt && time < endt) {
$("#a").append("<br> show Box ");
} else {
$("#a").append("<br> Expire BOx ");
}
}
Try this.
I took the logic to print 'Show Box' if the current time is in between the start and end time. else viceversa.
var startTime="20:02:55"; // or 12:34
var endTime ="21:02:55" // or 1:34
var dt = new Date();
var st = new Date('00','00','00',startTime.split(':')[0],startTime.split(':')[1],startTime.split(':')[2]);
var et = new Date('00','00','00',endTime.split(':')[0],endTime.split(':')[1],endTime.split(':')[2]);
if(dt.getTime() >st.getTime() && dt.getTime() < et.getTime()){
alert("show Box");
}else{
alert("Expire BOx");
}