I'm trying to make a site that displays a different line of text depending on the hour (GMT). I have tried using javascript, but I'm very much a beginner! I've managed to piece the following bit of code together but can't seem to get it to work. Any help appreciated!
function getTime(zone, success) {
var url = 'http://json-time.appspot.com/time.json?tz=' + zone,
ud = 'json' + (+new Date());
window[ud]= function(o){
success && success(new Date(o.datetime));
};
document.getElementsByTagName('head')[0].appendChild((function(){
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = url + '&callback=' + ud;
return s;
})());
}
getTime('GMT', function(time){
if (time>10 && time<11)
{
document.write("<b>Paris</b>");
}
;
});
Javascript has a Date class.
var hour = new Date().getHours();
if(...) {
// do something
}
This code extract
if (hour>10 && hour<11)
can't be working with hours, because time can't be > 10 and < 11 at the same time (hour is an int).
How about:
var now = new Date();
var utcMillis = now.getTime() + now.getTimzoneOffset() * 60000;
var hour = new Date(utcMillis).getHours(); // 0-23
switch(hour) {
case 10: document.write("<b>Paris</b>"); break;
//...
}
Some good info here: http://www.techrepublic.com/article/convert-the-local-time-to-another-time-zone-with-this-javascript/6016329
You could also put your phrases in an array (which you might get from the server):
var phrases = ["Hi!", "blah", "more blah", ...];
... and then you can replace the switch above with:
document.write("<b>" + phrases[hour] + "</b>");
You might want to save yourself some time and use a framework that makes things work pretty much the same way across different browsers. JQuery is my favorite, but there are plenty. Such libraries make it easy to manipulate content in your page, fetch JSON from the server, etc etc.
At first sight:
o.datetime is wrong formatted for JS Date method.
you return an instance of new Date() to get the hour use .getHours()
You can look here to find a way to convert your dateString from o.datetime How can I convert string to datetime with format specification in JavaScript?
Use time.getHours() > 12 instead of time > 12
If you use: getDateFromFormat() from http://www.mattkruse.com/javascript/date/ I think the conversion will be something like E, dd MMM hh:mm:ss +0000
SIMPLE ANSWER:
You can just parse the hour to your callback: (See your JSON here http://json-time.appspot.com/time.json?tz=GMT)
function getTime(zone, success) {
var url = 'http://json-time.appspot.com/time.json?tz=' + zone,
ud = 'json' + (+new Date());
window[ud]= function(o){
success && success(o.hour); // See o.hour here
};
document.getElementsByTagName('head')[0].appendChild((function(){
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = url + '&callback=' + ud;
return s;
})());
}
getTime('GMT', function(time){
if (time>10 && time<11) {
document.write("<b>Paris</b>");
}
});
I've created a quick jsfiddle page: http://jsfiddle.net/eBAGS/5/ with a demo that should do what you need. It gets the time from the users PC rather than from a server though, but it could be modified.
HTML
<button onClick="getPhrase()">Show me a phrase for this hour</button>
<div id="placeHolder"></div>
Javascript
function getPhrase() {
h = new Date().getHours(); //Get the current hour
phrase = new Array(); //Create an array of phrases
phrase[1] = 'Hello';
phrase[2] = 'there';
phrase[3] = 'this';
phrase[4] = 'will';
phrase[5] = 'show';
phrase[6] = 'a';
phrase[7] = 'different';
phrase[8] = 'message';
phrase[9] = 'depending';
phrase[10] = 'on';
phrase[11] = 'the';
phrase[12] = 'hour';
phrase[13] = 'of';
phrase[14] = 'day';
phrase[15] = 'that';
phrase[16] = 'you';
phrase[17] = 'look';
phrase[18] = 'at';
phrase[19] = 'it';
phrase[20] = '!';
phrase[21] = 'W';
phrase[22] = 'X';
phrase[23] = 'Y';
phrase[24] = 'Z';
document.getElementById('placeHolder').innerHTML = phrase[h-1]; //Show the array item relevant to the hour
}
Related
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);
});
I would like to create a simple if / else statement with JS. That would check if a div element has changed, before populating JSON data fields / variables that pull from dynamically changed HTML.
I do not want to use the DOMSubtreeModified. As it's depreciated..
Below is the started logic, I have. But it looks like I'll have to scrap the DOMSubtreeModified out for a method that is not depreciating.
The question / problem is: How to re-write not using the above depreciated technique, and how to nest my data array, where it will only pull / populate based on first checking my if (condition) Cheers for any pointers.
var element = document.querySelector('.username'); // username div wrapper
//if {
element.addEventListener('DOMSubtreeModified', function() { // detect if div element changes
var date = new Date();
var month = date.getUTCMonth() + 1;
var day = date.getUTCDate();
var year = date.getUTCFullYear();
var time = date.toLocaleTimeString();
var formattedDate = month + '/' + day + '/' + year;
console.log(time); // 7:01:21 PM
console.log(formattedDate); // 3/15/2016
}, false);
// change something on element
setTimeout(function() {
element.dataset.username = 'bar';
}, 3000);
// json object with captured data fields
var NewUserSession = [{
currentusername: $('.username').text(),
referrer: document.referrer,
loggedintime: $(formattedDate),
}];
//}
//
//else {
//
//
//}
You can use MutationObserver and watch for data-username changes
var element = document.querySelector('.username'); // username div wrapper
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.attributeName = 'data-username') {
var date = new Date();
var month = date.getUTCMonth() + 1;
var day = date.getUTCDate();
var year = date.getUTCFullYear();
var time = date.toLocaleTimeString();
var formattedDate = month + '/' + day + '/' + year;
snippet.log(time); // 7:01:21 PM
snippet.log(formattedDate); // 3/15/2016
}
});
});
var config = {
attributes: true,
attributeFilter: ['data-username']
};
// pass in the target node, as well as the observer options
observer.observe(element, config);
// change something on element
setTimeout(function() {
element.dataset.username = 'bar';
}, 1000);
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<div class="username"></div>
I am using Moment.js to track the duration of an action in my app. Currently, I have the following code:
var startMoment = null;
var actionClock = null;
function startClock() {
actionClock = setInterval(function(){
if (startMoment === null) {
startMoment = moment();
$('#duration').text('00:00:00');
} else {
var now = moment();
var span = moment.duration(now - startMoment);
$('#duration').text(span.minutes() + ':' + span.seconds() + '.' + span.milliseconds());
}
}, 1000);
}
function stopClock() {
clearInterval(actionClock);
var now = moment();
var span = moment.duration(now - startMoment);
$('#duration').text(span.minutes() + ':' + span.seconds() + '.' + span.milliseconds());
startMoment = null;
actionClock = null;
}
My problem is, the format of duration is awkward. I want to display the duration as mm:ss.lll. In other words, always show two digits for the minutes, two digits for the seconds, and three digits for the milliseconds. Currently, I see durations printed like 1:2.45. How do I format a duration created with Moment.js? If this is not possible, is there another library I should be using to track a duration and display it?
Thank you!
One way of doing this might be to convert your duration back into a moment (perhaps using milliseconds), and then using the moment's formatting.
moment.utc(span.asMilliseconds()).format('mm:ss.SSS');
var startMoment = null,
$durForm = $('#durationFormatted');
var actionClock = null;
function startClock() {
actionClock = setInterval(function() {
if (startMoment === null) {
startMoment = moment();
$('#duration').text('00:00:00');
$durForm.text('00:00.000');
} else {
var now = moment();
var span = moment.duration(now - startMoment);
$('#duration').text(span.minutes() + ':' + span.seconds() + '.' + span.milliseconds());
$durForm.text(moment(span.asMilliseconds()).format('mm:ss.SSS'));
}
}, 1000);
}
function stopClock() {
clearInterval(actionClock);
var now = moment();
var span = moment.duration(now - startMoment);
$('#duration').text(span.minutes() + ':' + span.seconds() + '.' + span.milliseconds());
$durForm.text(moment(span.asMilliseconds()).format('mm:ss.SSS'));
startMoment = null;
actionClock = null;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>
<div>Duration (original): <span id='duration'></span>
</div>
<div>Formatted moment: <span id='durationFormatted'></span>
</div>
<button onClick='startClock()'>Start Clock</button>
<button onClick='stopClock()'>Stop Clock</button>
I had a similar issue in my project and thankfully, Lodash was already a dependency. I was able to use the _.padStart method to get there.
let yourHours = _.padStart(span.hours().toString(),2,'0');
let yourMinute = _.padStart(span.minutes().toString(),2,'0');
let yourSeconds = _.padStart(span.seconds().toString(),2,'0');
I tried create markers by JSON parse from C #.I have a small problem about datetime compare in javascript.
var nowDate= new Date();
var LastTenMin= new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(),nowDate.getHours(),nowDate.getMinutes()- 10);
var Time1= data2.LastRecordTime;
var image2;
var status;
if (new Date(Time1) < new Date(LastTenMin)) {
image2 = '/Images/truckOnline.png';
status = "Truck is online."+"\n"+"Last seen:"+" "+Time1,
}
else {
image2 = '/Images/truckOffline.png';
status = "Truck is offline"+"\n"+"Last seen:"+" "+Time1,
}
else is not working ! There are truckOnline markers on google map.Where is my mistake ?
And LastRecordTime format like this in SQL : 04.12.2013 01:03:00
LastRecordTime=CONVERT(VARCHAR(10), [ReadTimeColumn], 104) + ' ' + CONVERT(VARCHAR(8), [ReadTimeColumn],108)
Mehmet,
Looks like you made a typo:
var LastTenMin= new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(),nowDate.getHours(),nowDate.getMinutes(),- 10);
Should be (note the comma):
var LastTenMin= new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(),nowDate.getHours(),nowDate.getMinutes() - 10);
Also you were trying to create a new date object from a date object, this is incorrect:
new Date(LastTenMin)
And here is a more complete solution:
var nowDate= new Date();
var Time1 = new Date("04/12/2013 01:03:00");
var LastTenMin= new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(), nowDate.getHours(), nowDate.getMinutes() - 10);
// Should return true
console.log(Time1 < LastTenMin);
// Change the year to a point in the future
Time1 = new Date("04/12/2014 01:03:00");
// Shold return false
console.log(Time1 < LastTenMin);
// So your original conditional should look like this:
if (Time1 < LastTenMin) {
image2 = '/Images/truckOnline.png';
status = "Truck is online."+"\n"+"Last seen:"+" "+Time1;
} else {
image2 = '/Images/truckOffline.png';
status = "Truck is offline"+"\n"+"Last seen:"+" "+Time1;
}
// And a more concise form:
var isOnline = !(Time1 < LastTenMin);
var image2 = isOnline ? '/Images/truckOnline.png' : '/Images/truckOffline.png';
var status = "Truck is " + (isOnline ? "Online" : "Offline") + "." + "\n" + "Last seen:" + " " + Time1
Here is the solution without comments:
var nowDate= new Date();
var Time1 = new Date(data2.LastRecordTime);
var LastTenMin= new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(), nowDate.getHours(), nowDate.getMinutes() - 10);
var isOnline = !(Time1 < LastTenMin);
var image2 = isOnline ? '/Images/truckOnline.png' : '/Images/truckOffline.png';
var status = "Truck is " + (isOnline ? "Online" : "Offline") + "." + "\n" + "Last seen:" + " " + Time1
My whole solution is assuming that the string contained in data2.LastRecordTime is in the format: "MM.DD.YYYY HH:MM:SS".
This is going to sound like a cop out, but I would switch to MomentJS so you get the following code:
var Time1 = moment("04/12/2013 01:03:00");
var lastTenMin = moment().subtract({minutes: 10});
if(Time1.isBefore(lastTenMin)){
image2 = '/Images/truckOnline.png';
status = "Truck is online."+"\n"+"Last seen:"+" "+Time1.local();
} else {
image2 = '/Images/truckOffline.png';
status = "Truck is offline"+"\n"+"Last seen:"+" "+Time1.local();
}
Remember, JavaScript has random off-by-one issues for the date and month (one is zero-based, the other is one-based). The problem most likely is in this line:
var LastTenMin= new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(),nowDate.getHours(),nowDate.getMinutes()- 10);
If you switch to MomentJS, these kind of problems will disappear. I have lost many hours fighting these same issues, so I understand!
P.S. Try out the calendar() formatting feature... it may be a good fit in your UI.
To compare dates with time in Javascript we need to pass them in Date object as "yyyy/mm/dd HH:mm" format for e.g. like "2014/05/19 23:20" . Then you can just compare them with > or < less then symbol according to your business rule. Please see given below code for more understanding.
$(function () {
$("input#Submit").click(function () {
var startDateTime = $("input[name='StartDateTime']").val();
var endDateTime = $("input[name='EndDateTime']").val();
var splitStartDate = startDateTime.split(' ');
var splitEndDate = endDateTime.split(' ');
var startDateArray = splitStartDate[0].split('/');
var endDateArray = splitEndDate[0].split('/');
var startDateTime = new Date(startDateArray[2] + '/ ' + startDateArray[1] + '/' + startDateArray[0] + ' ' + splitStartDate[1]);
var endDateTime = new Date(endDateArray[2] + '/ ' + endDateArray[1] + '/' + endDateArray[0] + ' ' + splitEndDate[1]);
if (startDateTime > endDateTime) {
$("#Error").text('Start date should be less than end date.');
}
else {
$("#Error").text('Success');
}
});
});
You can also see a working demo here
I solved by SQL.
I set a new colum for difference minute between now and ReadTime.
DifferenceMinute=DATEDIFF(MINUTE,ReadTime,GETDATE())
if(DifferenceMinute>10)
{
bla bla
}
else
{
bla bla
}
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.