I am trying to display Time on my view with format 10: 30 PM PST from time stamp with format like '2012-10-10T06:42:47Z'. I tried different ways to do that and failed. Any good option to display time in that format?
My trail is here
$(document).ready(function() {
$("span.localtime").localtime();
});
(function() {
(function($) {
return $.fn.localtime = function() {
var fmtDate, fmtZero;
fmtZero = function(str) {
return ('0' + str).slice(-2);
};
fmtDate = function(d) {
var hour, meridiem;
hour = d.getHours();
if (hour < 12) {
meridiem = "AM";
} else {
meridiem = "PM";
}
if (hour === 0) { hour = 12; }
if (hour > 12) { hour = hour - 12; }
return hour + ":" + fmtZero(d.getMinutes()) + " " + meridiem + " " + (d.getMonth() + 1) + "/" + d.getDate() + "/" + d.getFullYear();
};
return this.each(function() {
var tagText;
tagText = $(this).html();
$(this).html(fmtDate(new Date(tagText)));
return $(this).attr("title", tagText);
});
};
})(jQuery);
}).call(this);
Related
I have a simple script that is supposed to show you the current date and supposed to leave a message based on the date. I am trying to get it so that I can display it, but also show that because the next month is upcoming, lets say the 25th and later, it would say that the next month is coming up. I am also not sure how to use a setinterval() to make the time look like its counting.
So far, this is what I have:
var message1 = "Have a nice week!";
var message2 = "The weekend is almost here!";
var message3 = "Enjoy the weekend !";
var dateText = "";
function output() {
var today = new Date();
var dd = today.getDate();
dayValue = today.getDay();
var mm = today.getMonth() + 1; //January is 0!
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
todaysDate = (mm + "/" + dd + "/" + yyyy);
if (dayValue == 0) {
dateText += "Sunday";
document.write("Today is: " + dateText + " " + todaysDate + " " + message3);
}
if (dayValue == 1) {
dateText += "Monday";
document.write("Today is: " + dateText + " " + todaysDate + " " + message1);
}
if (dayValue == 2) {
dateText += "Tuesday";
document.write("Today is: " + dateText + " " + todaysDate + " " + message1);
}
if (dayValue == 3) {
dateText += "Wednesday";
document.write("Today is: " + dateText + " " + todaysDate + " " + message1);
}
if (dayValue == 4) {
dateText += "Thursday";
document.write("Today is: " + dateText + " " + todaysDate + " " + message2);
}
if (dayValue == 5) {
dateText += "Friday";
document.write("Today is: " + dateText + " " + todaysDate + " " + message2);
}
if (dayValue == 6) {
dateText += "Saturday";
document.write("Today is: " + dateText + " " + todaysDate + " " + message3);
}
}
<body onLoad="output()" ;></body>
Thank you.
You could use setInterval to call your output function periodically, and then call that function onload.
Find the solution in the attached snippet.
var message1 = "Have a nice week!";
var message2 = "The weekend is almost here!";
var message3 = "Enjoy the weekend !";
function setOutput(){
setInterval(output, 3000);
}
function output() {
var today = new Date();
var dd = today.getDate();
var dayValue = today.getDay();
var mm = today.getMonth() + 1; //January is 0!
var yyyy = today.getFullYear();
var hh= today.getHours();
var MM= today.getMinutes();
var ss= today.getSeconds();
var dateText = "";
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
var todaysDate = (mm + "/" + dd + "/" + yyyy + " "+hh+":"+MM+":"+ss);
var titleElement = document.getElementById("title");
if (dayValue == 0) {
dateText += "Sunday";
titleElement.innerHTML = "Today is: " + dateText + " " + todaysDate + " " + message3;
}
if (dayValue == 1) {
dateText += "Monday";
titleElement.innerHTML ="Today is: " + dateText + " " + todaysDate + " " + message1;
}
if (dayValue == 2) {
dateText += "Tuesday";
titleElement.innerHTML ="Today is: " + dateText + " " + todaysDate + " " + message1;
}
if (dayValue == 3) {
dateText += "Wednesday";
titleElement.innerHTML ="Today is: " + dateText + " " + todaysDate + " " + message1;
}
if (dayValue == 4) {
dateText += "Thursday";
titleElement.innerHTML ="Today is: " + dateText + " " + todaysDate + " " + message2;
}
if (dayValue == 5) {
dateText += "Friday";
titleElement.innerHTML ="Today is: " + dateText + " " + todaysDate + " " + message2;
}
if (dayValue == 6) {
dateText += "Saturday";
titleElement.innerHTML ="Today is: " + dateText + " " + todaysDate + " " + message3;
}
}
<body onLoad="setOutput()" ;>
<div id="title"></div>
</body>
For this you can use moment js. In moment js, it is providing so many method for customisation like format, date, weekday and so many methods are available.
You can use on basis your requirements.
Here is below, I have created a demo, I hope this will help/guide you to achieve your requirement.
var msg = ["Have a nice week!", "The weekend is almost here!", "Enjoy the weekend !"], // As per your reuirement I have just only put into array.
weekDays = moment.weekdays(), //it will return all the weekname
date = moment(); //this will return today date
//this function will return text basis of week day number
function getMsg(d) {
let weekMsg = '';
switch (d.day()) {
case 1:
case 2:
case 3:
weekMsg = msg[0];
break;
case 4:
case 5:
weekMsg = msg[1];
break;
default:
weekMsg = msg[2];
}
return weekMsg;
}
//this function will put log on console..
function putConsole(d) {
console.log(`Today is : ${weekDays[d.day()]}, ${d.format("DD MMMM YYYY hh:mm:ss a")} ${getMsg(d)}`);
}
document.getElementById('title').innerHTML = `Today is : ${weekDays[date.day()]}, <b id="timer">${date.format("DD MMMM YYYY hh:mm:ss a")}</b> ${getMsg(date)}`
setInterval(function() {
date.add(1, 'seconds');
document.getElementById('timer').innerHTML = date.format("DD MMMM YYYY hh:mm:ss a");
}, 1000)
putConsole(moment('2018-03-11')); //For Sunday
putConsole(moment('2018-03-12')); //For Monday
putConsole(moment('2018-03-14')); //For Wednesday
putConsole(moment('2018-03-15')); //For Thursday
putConsole(moment('2018-03-16')); //For Friday
putConsole(moment('2018-03-17')); //For Saturday
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.7.0/moment.min.js"></script>
<div id="title"></div>
To add a different message at the end of the month, you just need to get the date using getDate and do a comparison, (new Date()).getDate() >= 25. As for creating a clock, you just create a function that updates the time on the page and then call it with setInterval. setInterval is really easy to use, you just pass a function to run, and an interval (in milliseconds). It returns the id of the timer that it creates, which you can store if you want to later stop the timer using clearInterval. In the example below, I am using toLocaleString to format the date instead of building up a string like your code does or using a library like moment.js like another answer suggested. document.write should be avoided, instead I am creating a separate element on the page for the message and the date/time and updating them independently when needed.
// the updateTimer variable will hold a function
// that is returned by this IIFE
const updateTimer = (function () {
let lastDate;
const elMotd = document.getElementById('motd');
const elDateTime = document.getElementById('datetime');
const dateOptions = {
weekday: 'long',
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric'
};
// return the function that will be stored in the global
// updateTimer variable.
// the `now` parameter defaults to a date object representing
// the current time/date if updateTimer is not passed any arguments.
return function updateTimer (now = (new Date())) {
let currentDate = now.getDate();
// only update the message of the day if
// the date has changed (or this is the first run
if (currentDate !== lastDate) {
lastDate = currentDate;
let motd;
// using a switch instead of multiple if/then statments
// can make things much simpler and easier to read
switch (now.getDay()) {
// Thur - Fri
case 4:
case 5:
motd = "The weekend is almost here!";
break;
// Sat - Sun
case 6:
case 0:
motd = "Enjoy the weekend!";
break;
// Mon - Wed
default:
motd = "Have a nice week!";
}
if (currentDate >= 25) {
motd = 'It is almost a new month. ' + motd;
}
elMotd.textContent = motd;
}
elDateTime.textContent = now.toLocaleString('en-US', dateOptions);
}
}());
// run updateTimer immediately so we don't have to wait one second
// for the first update
updateTimer();
// start a timer to update once a second
let timer = setInterval(updateTimer, 1000);
// the stuff below here is just here for the example
document.getElementById('first').addEventListener('click', () => {
clearInterval(timer);
let d = new Date();
d.setDate(1);
updateTimer(d);
}, false);
document.getElementById('twentysixth').addEventListener('click', () => {
clearInterval(timer);
let d = new Date();
d.setDate(26);
updateTimer(d);
}, false);
div {
margin: 1em;
padding: 1em;
border: #ccc solid 1px;
}
Today is: <span id="datetime"></span> <span id="motd"></span>
<!--the stuff below here is just here for the example -->
<div>
Stop timer and...
<button type="button" id="first">Set date to the first of the month</button>
<button type="button" id="twentysixth">Set date to the 26th of the month</button>
</div>
I want to format the time from 24 hours to 12 hours with AM/PM and display it in popover.
This is my code:
eventMouseover: function (event, jsEvent) {
var t1 = event.start;
var t2 = event.end;
$(this).popover({
html:true,
placement: 'left',
trigger: 'hover',
content: t1 + ' - ' + t2,
container: '#calendar'
}).popover('toggle');
}
I search for the answers here but it doesnt work in popover. So i decided to ask for it.
This is the code i used.
It works on here, but not in popover.
eventRender: function(event, element) {
var t1 = event.time;
var t2 = event.time2;
var tmpArr = t1.split(':'), time12;
if(+tmpArr[0] == 12) {
time12 = tmpArr[0] + ':' + tmpArr[1] + 'P';
} else {
if(+tmpArr[0] == 00) {
time12 = '12:' + tmpArr[1] + 'A';
} else {
if(+tmpArr[0] > 12) {
time12 = (+tmpArr[0]-12) + ':' + tmpArr[1] + 'P';
} else {
time12 = (+tmpArr[0]) + ':' + tmpArr[1] + 'A';
}
}
}
var tmpArrs = t2.split(':'), time13;
if(+tmpArrs[0] == 12) {
time13 = tmpArrs[0] + ':' + tmpArrs[1] + 'P';
} else {
if(+tmpArrs[0] == 00) {
time13 = '12:' + tmpArrs[1] + 'A';
} else {
if(+tmpArrs[0] > 12) {
time13 = (+tmpArrs[0]-12) + ':' + tmpArrs[1] + 'P';
} else {
time13 = (+tmpArrs[0]) + ':' + tmpArrs[1] + 'A';
}
}
}
element.find('.fc-content').append(t1 + "-" + t2 +);
}
Assuming you have moment.js included in your webpage (as FullCalendar needs it in any case) use the following code in place of declaring var t1 and var t2
var t1 = $.fullCalendar.moment(event.start).format("h:mm A")
var t2 = $.fullCalendar.moment(event.end ).format("h:mm A")
P.S. You don't need to work out the 12 hour format manually, moment.js does this for you
I've tried many ways to print out the MySQL default date time (0000-00-00 00:00:00) format in JavaScript. any help will be highly appreciated.
Thanks
you can break your date in date & time string and use as .
var date = '2017-12-11';
var time = '11:20:05';
var yourDateString = new Date(date + "T" + time+"Z");
console.log(yourDateString);
console.log(date2str(yourDateString,''));
function date2str(x, y) {
var z = {
YR: x.getFullYear(),
M: x.getMonth() + 1,
d: x.getDate(),
h: x.getHours(),
m: x.getMinutes(),
s: x.getSeconds()
};
{
var now = new Date();
var timeOpt = {hour:'2-digit', hour12:true, minute:'2-digit'};
var monthOpt = {day:'numeric', month:'short'};
var fullOpt = {day:'numeric', month:'short', year:'2-digit'};
if ( ((now - x) < 8.64e7) && (now.getDate() == z.d) ) {
var timeFragements = x.toLocaleString().toLowerCase();
if(null == timeFragements.match(/(\d+:\d+:\d+)+/)){
return x.toLocaleString("en-US", timeOpt).toLowerCase();
}
timeFragements =(timeFragements.match(/(\d+:\d+:\d+)+/)[0])
//Calculation of Am /Pm.
var hours = x.getHours();
var amPmStr = hours >= 12 ? ' pm' : ' am';
if(timeFragements.split(':')[0]<12){
return (("0" + timeFragements.split(':')[0]).slice(-2) +':'+ ("0" + timeFragements.split(':')[1]).slice(-2) + amPmStr );
}else if(timeFragements.split(':')[0]== 12){
return (("0" + (timeFragements.split(':')[0]) ).slice(-2) +':'+ ("0" + timeFragements.split(':')[1]).slice(-2) + amPmStr );
}else{
return (("0" + (timeFragements.split(':')[0]-12) ).slice(-2) +':'+ ("0" + timeFragements.split(':')[1]).slice(-2) + amPmStr );
}
} else if ( (now.getFullYear() == x.getFullYear()) && (now.getMonth() == x.getMonth()) ) {
return ("" + x.toDateString().split(' ')[1])+" "+("0" + x.getDate().toString()).slice(-2);
}else if( (now.getFullYear() == x.getFullYear()) && (now.getMonth() != x.getMonth())){
return ("" + x.toDateString().split(' ')[1])+" "+("0" + x.getDate().toString()).slice(-2);
}else if(now.getFullYear() !== x.getFullYear()){
return x.toUTCString().split(',')[1].slice(0, 12);
}
}
}
I'm struggling to figure out how Date() works, I found this on the web and wanted to make a countdown that stops at 21:57 UTC Time. It currently displays the message at 21:00 and apears until 22:00.
I tried to add if(currenthours != 21 && currentminutes >= 57){ and always broke it and got the message. I want it to stop 3 minutes before 22:00 and display the message. After it gets to 22:00 restart the countdown for the next day at 21:57.
Any help will be greatly appreciated !
var date;
var display = document.getElementById('time');
setInterval(function(){
date = new Date( );
var currenthours = date.getUTCHours();
// alert(currenthours);
var currentminutes = date.getUTCMinutes();
// alert(currentminutes);
var hours;
var minutes;
var secondes;
if (currenthours != 21) {
if (currenthours < 21) {
hours = 20 - currenthours;
} else {
hours = 21 + (24 - currenthours);
}
minutes = 60 - date.getUTCMinutes();
secondes = 60 - date.getUTCSeconds();
display.innerHTML = ('00' + hours).slice(-2) + ' HOURS ' + '<p>' +
('00' + minutes).slice(-2) + ' MINUTES ' + '</p>' +
('00' + secondes).slice(-2) + ' SECONDS';
} else {
display.innerHTML = "IT'S 21:57";
}
},1000);
<div id='time'></div>
Made a fiddle
https://jsfiddle.net/5qrs0tcp/1/
This is what I ended up with :
/*
|================================|
| COUNTDOWN TIMER |
|================================|
*/
// Return the UTC time component of a date in h:mm:ss.sss format
if (!Date.prototype.toISOTime) {
Date.prototype.toISOTime = function() {
return this.getUTCHours() + ':' +
('0' + this.getUTCMinutes()).slice(-2) + ':' +
('0' + this.getUTCSeconds()).slice(-2);
}
}
// Return the difference in time between two dates
// in h:mm:ss.sss format
if (!Date.prototype.timeDiff) {
Date.prototype.timeDiff = function(date2) {
var diff = Math.abs(this - date2);
return timeobj = {
hours : (diff/3.6e6|0), // hours
minutes : ('0' + ((diff%3.6e6)/6e4|0)).slice(-2), // minutes
seconds : ('0' + ((diff%6e4)/1e3|0)).slice(-2) // seconds
}
}
}
function countDown() {
var now = new Date();
var limitHr = 19;
var limitMin = 55;
var limitDate = new Date(+now);
// Set limitDate to next limit time
limitDate.setUTCHours(limitHr, limitMin, 0, 0);
// var msg = ['Currently: ' + now.toISOTime() + '<br>' + 'Limit: ' + limitDate.toISOTime()];
var msg = [];
var diff;
// If outside limitHr:limitMin to (limitHr + 1):00
if (now.getUTCHours() == limitHr && now.getUTCMinutes() >= limitMin) {
msg.push('Countdown stopped');
setTimeout(function(){
msg = ['Wait for it'];
var jsonCounter = {
stats : msg
}
jsonfile.writeFileSync(DailyGamePath, jsonCounter, {spaces: 3});
},5000);
var jsonCounter = {
stats : msg
}
jsonfile.writeFileSync(DailyGamePath, jsonCounter, {spaces: 3});
} else {
if (now > limitDate) limitDate.setDate(limitDate.getDate() + 1);
var jsonCounter = {
hours : now.timeDiff(limitDate).hours,
minutes : now.timeDiff(limitDate).minutes,
seconds : now.timeDiff(limitDate).seconds,
validating : msg
}
jsonfile.writeFileSync(DailyGamePath, jsonCounter, {spaces: 3});
}
}
setInterval(countDown, 1000);
var daily_status;
setTimeout( function(){
setInterval( function() {
jsonfile.readFile(DailyGamePath, (err, obj) => {
daily_status={
hours: obj.hours,
minutes: obj.minutes,
seconds: obj.seconds,
stats: obj.stats,
validating: obj.validating
};
return daily_status;
});
}, 1000);
}, 3000);
setTimeout( function(){
io.sockets.on('connection', (socket) => {
setInterval( function() {
// var GameStatus=DailyGameStatus();
socket.broadcast.emit('stream', {hours:daily_status.hours, minutes:daily_status.minutes, seconds:daily_status.seconds, stats:daily_status.stats, validating:daily_status.validating});
}, 1000);
});
}, 3000);
Date objects are very simple, they're just a time value and some handy methods.
I think your logic just needs to be:
if (currenthours != 21 && currentminutes < 57) {
// set the out of hours message
} else {
// time is from 21:57 to 21:59 inclusive
}
The countdown doesn't quite work because you're counting to 00 not to 57, but otherwise there doesn't seem to be an issue.
var date;
var display = document.getElementById('time');
setInterval(function(){
date = new Date( );
var currenthours = date.getUTCHours();
var currentminutes = date.getUTCMinutes();
var hours;
var minutes;
var secondes;
var limitHr = 5; // Change these to required values
var limitMin = 02; // Using 5:12 for convenience
var message = 'Currently: ' + date.toISOString() + '<p>';
// Create new message if outside limitHr:limitMin to limitHr:59 inclusive
if (currenthours != limitHr || currentminutes < limitMin) {
if (currenthours <= limitHr) {
hours = limitHr - currenthours;
} else {
hours = limitHr + (24 - currenthours);
}
minutes = limitMin - date.getUTCMinutes();
minutes += minutes < 0? 60 : 0;
secondes = 60 - date.getUTCSeconds();
message += ('00' + hours).slice(-2) + ' HOURS ' + '<p>' +
('00' + minutes).slice(-2) + ' MINUTES ' + '</p>' +
('00' + secondes).slice(-2) + ' SECONDS';
} else {
message += 'It\'s on or after ' + limitHr + ':' +
('0'+limitMin).slice(-2) + ' GMT';
}
// Display the message
display.innerHTML = message;
},1000);
<div id="time"></div>
Yes, the timer has issues but that wasn't part of the question. For a counter, it's simpler to just work in time differences, so I've added some methods to Date.prototype for ISO time (to be consistent with ISO Date) and time difference, then use those functions.
The function builds a Date for the end time so that calculations can use Date methods.
// Return the UTC time component of a date in h:mm:ss.sss format
if (!Date.prototype.toISOTime) {
Date.prototype.toISOTime = function() {
return this.getUTCHours() + ':' +
('0' + this.getUTCMinutes()).slice(-2) + ':' +
('0' + this.getUTCSeconds()).slice(-2) + '.' +
('00' + this.getUTCMilliseconds()).slice(-3) + 'Z';
}
}
// Return the difference in time between two dates
// in h:mm:ss.sss format
if (!Date.prototype.timeDiff) {
Date.prototype.timeDiff = function(date2) {
var diff = Math.abs(this - date2);
var sign = this > date2? '+' : '-';
return sign + (diff/3.6e6|0) + ':' + // hours
('0' + ((diff%3.6e6)/6e4|0)).slice(-2) + ':' + // minutes
('0' + ((diff%6e4)/1e3|0)).slice(-2) + '.' + // seconds
('00' + (diff%1e3)).slice(-3); // milliseconds
}
}
function countDown() {
var now = new Date();
var limitHr = 1;
var limitMin = 10;
var limitDate = new Date(+now);
// Set limitDate to next limit time
limitDate.setUTCHours(limitHr, limitMin, 0, 0);
var msg = ['Currently: ' + now.toISOTime() + '<br>' + 'Limit: ' + limitDate.toISOTime()];
var diff;
// If outside limitHr:limitMin to (limitHr + 1):00
if (now.getUTCHours() != limitHr || now.getUTCMinutes() != limitMin) {
if (now > limitDate) limitDate.setDate(limitDate.getDate() + 1);
msg.push(now.timeDiff(limitDate));
} else {
msg.push('It\'s after ' + limitHr + ':' + ('0'+limitMin).slice(-2));
}
document.getElementById('msgDiv2').innerHTML = msg.join('<br>');
}
window.onload = function() {
setInterval(countDown, 1000);
}
<div id="msgDiv2"></div>>
I've left the milliseconds in, round to seconds if you wish.
I've left the timer using setInterval, though I'd prefer to use setTimeout and manually calculate the time to just after the next full second so that it never skips. Most browsers using setTimeout will slowly drift so that they skip a second every now and then. Not really an issue unless you happen to see it, or compare it to the tick of the system clock.
I need a help.
I would like to see the last 24 hours in the timeline Chart. This is the formatted datetime DD/MM/YYYY HH:MM:SS.
This is the data source: https://docs.google.com/spreadsheets/d/1H602ZpDfwl044qjDyIDfscOWoaSqLzjsvb3TuZXEK6c/edit#gid=0
I'm getting en error: Uncaught SyntaxError: Unexpected token ILLEGAL
Does anyone have any idea to solve this?
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization',
'version':'1','packages':['timeline']}]}"></script>
<script type="text/javascript">
google.setOnLoadCallback(drawChart);
function drawChart() {
var dataTable = new google.visualization.DataTable();
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1H602ZpDfwl044qjDyIDfscOWoaSqLzjsvb3TuZXEK6c/edit#gid=0');
var nowone = getNowDate();
query.setQuery("select A,B,C where B >= datetime '"+nowone+"' ");
query.send(handleQueryResponse);
}
function getNowDate(){
var d=new Date();
d.setDate(d.getDate() - 1);
var year = d.getFullYear();
var month = d.getMonth() + 1;
var day = d.getDate();
var hour = d.getHours();
var minute = d.getMinutes();
var second = d.getSeconds();
var microsecond = d.getDate();
if (month.toString().length == 1) {
month = '0' + month;
}
if (day.toString().length == 1) {
day = '0' + day;
}
if (hour.toString().length == 1) {
hour = '0' + hour;
}
if (minute.toString().length == 1) {
minute = '0' + minute;
}
if (second.toString().length == 1) {
second = '0' + second;
}
//while(microsecond.toString().length < 3) {
// microsecond = '0' + microsecond;
//}
var dateString = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second';
return dateString;
}
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var options = {
timeline: { singleColor: '#8d8' },
};
var container = document.getElementById('example5.2');
var chart = new google.visualization.Timeline(container);
chart.draw(data, options);
setTimeout(drawChart, 5000);
}
</script>
</head>
<body>
<div id="example5.2" style="height: 500px;"></div>
</body>
</html>
This is purely a JS issue. You have an extra quote in JS that doesn't belong. When you set your time, it should be:
var dateString = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
Instead of
var dateString = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second';
If you remove the extraneous quote, your error will go away.