I am trying to get a date to refresh on a page so I don't have to go and manually refresh it everyday. I have this code in place, but it doesn't seem to be working. The date displays, but it doesn't update when the day changes. For reference, this is being used on a BrightSign display. Can anyone tell me what I'm doing wrong? I'm kind of a JavaScript beginner so nothing too complex :)
<script type="text/javascript">
<!--
function clockTick() {
currentTime = new Date();
month = currentTime.getMonth() + 1;
day = currentTime.getDate();
year = currentTime.getFullYear();
setInterval(clockTick, 1000);
return (month + "/" + day + "/" + year);
}
document.write(clockTick());
//-->
</script>
You will want to take the setInterval out of the function and set the time on the page inside the function so that it refreshes every second:
function clockTick() {
var currentTime = new Date(),
month = currentTime.getMonth() + 1,
day = currentTime.getDate(),
year = currentTime.getFullYear(),
hours = currentTime.getHours(),
minutes = currentTime.getMinutes(),
seconds = currentTime.getSeconds(),
text = (month + "/" + day + "/" + year + ' ' + hours + ':' + minutes + ':' + seconds);
// here we get the element with the id of "date" and change the content to the text variable we made above
document.getElementById('date').innerHTML = text;
}
// here we run the clockTick function every 1000ms (1 second)
setInterval(clockTick, 1000);
<span id="date"></span>
you can try this:call clockTick() from outside.
function clockTick() {
currentTime = new Date();
month = currentTime.getMonth() + 1;
day = currentTime.getDate();
year = currentTime.getFullYear();
// alert("hi");
document.getElementById('date').innerHTML=month + "/" + day + "/" + year;
}
setInterval(function(){clockTick();}, 1000);//setInterval(clockTick, 1000); will also work
<div id="date"></div>
Related
I have to get Browser Local date and time with Javascript and compare it in PHP IF statement with value from database on page load to determine if product expired or not. How do I solve the issue without using cookies and or sessions?
Javascript
<script>
var currentDate = new Date(),
day = ('0' + (currentDate.getDate()+1)).slice(-2),
month = ('0' + (currentDate.getMonth()+1)).slice(-2),
year = currentDate.getFullYear();
var currentTime = new Date(),
hours = currentTime.getHours(),
minutes = currentTime.getMinutes();
if (minutes < 10) {
minutes = '0' + minutes;
}
document.write(day + '/' + month + '/' + year + ' ' + hours + ':' + minutes)
</script>
PHP
if(strtotime( date and time from SCRIPT ) < strtotime($events date and time exiptation as $events_total_SKU[$e]['sales_end']))
{
print(" OK ");
.... and shopping cart code
}
else{
print(" Expired ");
}
You should store both the dates in JavaScript variables as below. And compare it in Js as well.
var currentDate = new Date(),
day = ('0' + (currentDate.getDate()+1)).slice(-2),
month = ('0' + (currentDate.getMonth()+1)).slice(-2),
year = currentDate.getFullYear();
var currentTime = new Date(),
hours = currentTime.getHours(),
minutes = currentTime.getMinutes();
var frontendDate = year + '-' + month + '-' +day + ' ' + hours + ':' + minutes;
var backednDateString = "<?php echo $events_total_SKU[$e]['sales_end'];?>";
// As backedn date is string convert it as date first.
var backednDateS = new Date(backednDateString );
if(frontendDate < backednDate)
{
alert(" OK ");
}
else{
alert(" Expired ");
}
Make sure format of both the dates are same.
I'm using ASP.NET and I have the following string:
2018-12-04T13:53:42.6785734+07:00
I want to convert the string to Date object and format the output string.
My goal: 04/12/2018 13:53:42
I've tried this way but it logged with the wrong result:
var dt = new Date('2018-12-04T13:53:42.6785734+07:00');
var day = dt.getDay(),
month = dt.getMonth(),
year = dt.getFullYear(),
hours = dt.getHours(),
minutes = dt.getMinutes(),
seconds = dt.getSeconds();
// 2/11/2018 13:53:42
console.log(day + '/' + month + '/' + year + ' ' + hours + ':' + minutes + ':' + seconds);
var dt = new Date('2018-12-04T13:53:42.6785734+07:00');
var day = dt.getDate(),
month = dt.getMonth(),
year = dt.getFullYear(),
hours = dt.getHours(),
minutes = dt.getMinutes(),
seconds = dt.getSeconds();
// 2/11/2018 13:53:42
console.log(day + '/' + (month + 1) + '/' + year + ' ' + hours + ':' + minutes + ':' + seconds);
I changed your code like this, try:
var dt = new Date('2018-12-04T13:53:42.6785734+07:00');
var day = dt.getDate(),
month = dt.getMonth(),
year = dt.getFullYear(),
hours = dt.getHours(),
minutes = dt.getMinutes(),
seconds = dt.getSeconds();
console.log(day + '/' + (month + 1) + '/' + year + ' ' + hours + ':' + minutes + ':' + seconds);
Would it be acceptable to just manipulate the original string directly without converting to a date object like so? I can really tell what the test cases would be but assuming that the hour number is the same length (04,12) I think the following code should work.
let dt = '2018-12-04T13:53:42.6785734+07:00';
let dArr = dt.substr(0,10).split('-');
let year = dArr[0];
let month = dArr[1];
let day = dArr[2];
let time = dt.substr(11,8);
let str = month+'/'+day+'/'+year+' '+time;
console.log(str)
The following are arrays starting at 0
getDay() Get the weekday as a number (0-6)
getDate() Get the day as a number (1-31)
getMonth() Get the month as a number (0-11)
var dt = new Date("2018-12-04T13:53:42.6785734+07:00");
var day = returnDay(),
month = returnMonth(),
year = dt.getFullYear(),
hours = dt.getHours(),
minutes = dt.getMinutes(),
seconds = dt.getSeconds(),
function returnDay(){
var d = (dt.getDate() < 10) ? "0" + (dt.getDate()): dt.getDate();
return d;
}
function returnMonth(){
var m = (dt.getMonth() + 1 < 10) ? "0" + (dt.getMonth()+ 1):dt.getMonth()+ 1;
return m;
}
//04/12/2018 8:53:42
console.log(day + '/' + month + '/' + year + ' ' + hours + ':' + minutes + ':' + seconds);
see for more info:
https://www.w3schools.com/js/js_date_methods.asp
Slice it, I have used jQuery in the example because I have used in in another project and this code was just a part of a component, but it should not matter much
var getTimeOnly = new Date().getTime();
var fullDate = new Date($.now()).toString();
var datePartialTime = fullDate.slice(16, 25);
var datePartialDate = fullDate.slice(0, 16);
$('a').html( "on " + datePartialDate + 'at ' + datePartialTime);
Link to pen
https://codepen.io/damPop/pen/zMzBGN
I am trying to get the day 90 days after today. This is my code:
var today = new Date();
var threeMonthsFromToday = new Date(today.setDate(today.getDate() + 90));
When I print threeMonthsFromToday, I get the correct date: 2017-04-24T15:17:42.641Z. However, when I try to reformat the date to be in the form dd/mm/yyyy using this code:
var day = ('0' + threeMonthsFromToday.getDate()).slice(-2);
var month = ('0' + threeMonthsFromToday.getMonth() + 1).slice(-2);
var year = threeMonthsFromToday.getFullYear();
var date = day + '/' + month + '/' + year;
I get a completely different and invalid date: 24/31/2017.
I have been debugging this for hours and still can't seem to figure what I am doing wrong.
Well, '0' + threeMonthsFromToday.getMonth() give you a string : "03" then you add 1 converted to string giving you "031" for month before slice.
Use this :
var month = ('0' + (threeMonthsFromToday.getMonth() + 1)).slice(-2);
You are missing the basic BODMAS rule here please modify your code as follows
var today = new Date();
var threeMonthsFromToday = new Date(today.setDate(today.getDate() + 90));
var day = ('0' + threeMonthsFromToday.getDate()).slice(-2);
var month = ('0' + (threeMonthsFromToday.getMonth() + 1)).slice(-2);
var year = threeMonthsFromToday.getFullYear();
var date = day + '/' + month + '/' + year;
the operations are performed from left to right, so month is getting converted to string before being added to a number. Including a bracket will first perform operation inside bracket and then make it a string
Can you use toLocaleString?
threeMonthsFromToday.toLocaleDateString('en-GB')
Below does the trick for you ...
getMonth() +1 before adding the "0" to it so that you get an arithematic +1
var today = new Date();
var threeMonthsFromToday = new Date(today.setDate(today.getDate() + 90));
var day = ('0' + threeMonthsFromToday.getDate()).slice(-2);
var month = ('0' + (threeMonthsFromToday.getMonth()+1)).slice(-2);
var year = threeMonthsFromToday.getFullYear();
var date = day + '/' + month + '/' + year;
console.log(date);
This should work.
var day = threeMonthsFromToday.getDate()
if(day < 10){
day = '0' + day
}
var month = threeMonthsFromToday.getMonth()+1
if(month<10){
month = '0' + month
}
var year = threeMonthsFromToday.getFullYear()
var date = day + '/' + month + '/' + year
Use Simple toLocaleDateString method
The toLocaleDateString() method returns a string with a language sensitive representation of the date portion of this date.
var today = new Date();
var threeMonthsFromToday = new Date(today.setDate(today.getDate() + 90));
var date = threeMonthsFromToday.toLocaleDateString();
console.log(date);
//result in console : "24/04/2017"
Try it out on your console.
I have one case related to fullCalendar control. I am showing Days from Mon-Fri and there is Custom Button added named as Add new Appointment. When user clicks on this button we need to show First Monday date for Month view and if it is Week view we need to show 1st date(Monday) of that week. '
I have done this way till now it's working for IST time Zone but my client is CST/EST and it takes previous day. Example- on Month view if i go to Feb and click on Add new it should 02-02-2016 but it's taking 01-31-2015.
function processDateTimeForNewCalendar() {
debugger;
var mondayForWeek = common.getMondayForCurrentWeek(new Date());
var dateHeader = $('div.fc-center h2').text();
var view = $('#calendar').fullCalendar('getView');
var date, sTime, eTime;
var currentDate = new Date();
if (view.name === 'month') {
debugger;
var currentMonth = dateHeader.split(" ")[0];
var currentYear = dateHeader.split(" ")[1];
var monthInNo = common.getMonthNumberByMonthName(currentMonth);
var temp = currentDate.getDate() + "-" + currentMonth + "-" + currentYear + " " + currentDate.getHours() + ":" + currentDate.getMinutes()
var tempDate = new Date(temp);
var mondayForWeek = common.getMondayForCurrentWeek(tempDate);
if ((currentDate.getMonth() + 1) === monthInNo)
date = new Date(currentDate.getDate() + "-" + currentMonth + "-" + currentYear + " " + currentDate.getHours() + ":" + currentDate.getMinutes());
if ((currentDate.getMonth() + 1) < monthInNo || (currentDate.getMonth() + 1) > monthInNo)
date = new Date(view.intervalStart);
sTime = moment(date).format("hh:mm A");
eTime = moment(date).add(30, 'minutes').format("hh:mm A");
}
if (view.name === 'agendaWeek' || view.name === 'agendaDay') {
date = new Date(view.start);
date = moment(date).format("MM/DD/YYYY");
sTime = moment(currentDate).format("hh:mm A");
eTime = moment(currentDate).add(30, 'minutes').format("hh:mm A");
}
$(CALENDAR.ApptStartDateById).val(moment(date).format("MM/DD/YYYY"));
$(CALENDAR.ApptEndDateById).val(moment(date).format("MM/DD/YYYY"));
$(CALENDAR.ApptStartTime).timepicker("setTime", sTime);
$(CALENDAR.ApptEndTime).timepicker("setTime", eTime);
$(CALENDAR.Duration).val(calculateDuration());
$(CALENDAR.ApptStartDateById).datepicker("update", date).datepicker('fill');
$(CALENDAR.ApptEndDateById).datepicker("update", date).datepicker('fill');
}
Please help me fix this.
Thanks,
Amod
You can use $('calendar selector').fullCalendar('getView').start to get the starting date of your current view;
I have done it in other way by finding the first Day of the Month and checks if it is sunday. If it is then add +1 day. Check the code below-
function getFirstDayOfMonth(d) {
d.setMonth(d.getMonth(), 1);
// if sunday add +1 day
if (d.getDay() === 0)
d.setDate(d.getDate() + 1, 1);
return d;
}
Hope, this is the alternate solution for finding first day of month using fullCalendar.
I'm using a script to display the current date to someone, but I want to do two things to it.
First, I want to change the format to MM/DD/YY, so it's only showing the year in 2 digits.
Then second, how can I add a default? So if it's not able to be pulled by someone, it will show "Today" instead of a date?
Here's the script if anyone could help:
var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
document.write(month + "/" + day + "/" + year)
Working FIDDLE Demo
Add a div to your HTML and put your default text inside it:
<div id="date">Today</div>
Then with javascript, change it, and if the user don't have javascript, it remains not changed:
// create date
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var date = month + "/" + day + "/" + (year + '').substring(2);
// now insert it
document.getElementById('date').innerHTML = date;
[!] Don't forget to add the JS after your element or add it to document ready.
I don't see any reason for this to fail, If javascript is enabled in the client it should work, still if you want error handling
try {
var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
document.write(month + "/" + day + "/" + (year + '').substring(2))
}catch(e){
document.write('Today');
}
You can get the last two digits of day by doing String(year).substring(2,4). So you end up with:
console.log(day+"/"+month+"/"+String(year).substring(2,4));
To set defaults you can use the following:
var demo = value1 || default
You can play around with these ideas here