I am using timeago.js to show the date. However, I want to show the "hours ago" feature of the plugin if a particular date is less than 2 days. If a date is more than 2 days, it'll show the usual "3 days ago".
Thanks for the help in advance.
Apparently, I have to modify the plugin. Have to set the "hours" to be less than 48 hours.
var words = seconds < 45 && substitute($l.seconds, Math.round(seconds)) ||
hours < 48 && substitute($l.hours, Math.round(hours)) ||
You can of course modify plugin like you did, or you could run the dates over again and check whether they are more than two days or not - if they are - just rewrite the string to hours, something like this:
$(function(){
var oneHour = 1*60*60*1000; // one hour in miliseconds
var twoDays = 2*24*oneHour; // two days in miliseconds
$('.timeAgoSelector').each(function(){
$t = $(this);
var agoDate = new Date( $t.attr('title') ).getTime()
var currDate = new Date().getTime();
var timeAgo = currDate - agoDate;
if( (timeAgo < twoDays) && (timeAgo >= oneHour) ){
var hours = ((timeAgo/1000)/60)/60;
hours = Math.floor(hours);
if( hours < 2 ) $t.html( 'an hour ago' );
else $t.html( hours + ' hours ago' );
} //else => do nothing (keep original content)
});
});
=> http://jsfiddle.net/chgvcudL/
I think timeago.js can help you, and the tiny library is supported by me.
You can just customize you locale function for your need.
const yourLocale = (number, index, totalSec) => {
// format totalSec into hours.
const hours = getHours(totalSec);
return hours +' hours ago';
};
Then register it.
timeago.register('yourLocale', yourLocale);
Them format use it.
timeago.format(time, 'yourLocale');
done!
Related
I'm trying to write a statement that says "if time is this and less than that then". I can use get hours and get min. However, I'm having problems combining a time such as 9:30.
Example,
var now = new Date();
var hour = now.getHours();
var day = now.getDay();
var mintues = now.getMinutes();
if (day == 0 && hour >= 9 && hour <= 11 && mintues >= 30) {
document.write(now);
}
This only if the time is less between 9:30 10. As soon as the clock hits 10 the minutes are then < 30 and the script breaks.
Any thoughts on how to better incorporate the time function to make this theory work?
Thanks,
use new Date().getTime() returns milliseconds for much easier comparison. This way there is no need to check hour, min, second, millisecond. Fiddle link
var d930 = new Date(2010, 12, 21, 9, 30, 0, 0), // today 9:30:00:000
d931 = new Date(2010, 12, 21, 9, 31, 0, 0), // today 9:31:00:000
t930 = d930.getTime(),
t931 = d931.getTime();
console.log(t931 > t930);
This way your code can check against a static 9:30 time.
var time930 = new Date(2010, 12, 21, 9, 30, 0, 0).getTime(),
sunday = 0,
now = new Date();
if(now.getDay() == sunday && now.getTime() >= time930){
/* do stuff */
}
You have a few typos and basic javascript errors.
Might wanna brush up on the basics.
W3Schools is where I learned all I know.
It works fine if you fix them...
var now = new Date();
var hour = now.getHours();
var day = now.getDay();
var minutes = now.getMinutes();
if(day == 0 && hour == 9 && minutes < 30 && minutes > 10 || day == 0 && hour == 9)
document.write('Time is between 9:10 and 9:30');
Think of the if statement as basic logic.
If the day is Sunday(0)
AND the hour is 9
AND the minutes are greater than 10
AND the minutes are less than 10
OR the day is Sunday(0)
AND the hour is before 9.
var now = new Date();
var closeTime = new Date();
closeTime.setHours(9); closeTime.setMinutes(30);
console.log(now, closeTime, now.getTime() >= closeTime.getTime());
close time is based on today, then we just change the hours and minutes to 9:30.
I made this solution simple and easy to read (thus easy to adjust).
// we need a function that makes hours and minutes a two digit number
Object.prototype.twoDigits = function () {
return ("0" + this).slice(-2);
}
// get current date and time
let now = new Date();
// compile the current hour and minutes in the format 09:35
timeOfDay = now.getHours().twoDigits() + ':' + now.getMinutes().twoDigits();
// test if timeOfDay is within a given time frame
if ('09:30' <= timeOfDay && timeOfDay <= '11:30') {
console.log('inside time frame');
} else {
console.log('outside time frame');
}
I had a similar problem to solve today, I setup a little component that returns if a place of business is open or not. Got the time by dividing the minutes by 100 then adding it to the hours. So 8:30 is represented as 8.3
let d = new Date()
let day = d.getDay()
let hours = d.getHours()
let minutes = d.getMinutes() / 100
let time = hours + minutes
if (day == 1) {
if (time > 8.3 && time < 17.3) {
setIsOpen(true)
} else {
setIsOpen(false)
}
}
if the hour is less than 9, true
or
if hour is 9 and minutes lt 30, true
so that would look like
if ((hour < 9) || (hour == 9 && minutes < 30))
Use words to figure out your logic. Symbols are just shortcuts.
One way is to do a direct comparison on date objects. Choose an arbitrary year, month and day, and then incorporate your times as follows:
var older = new Date("1980-01-01 12:15");
var newer = new Date("1980-01-01 12:30");
if (newer > older){
alert("Newer time is newer");
} else {
alert ("The time is not newer");
}
The MDC documentation on the Date object will help with some more details. The bottom line is that if you want to compare times, you don't actually need to call any methods on the objects, and it's possible to directly compare them. The date() object can take a variety of strings to assign a new time to the returned instance, these are from the MDC documentation:
today = new Date();
birthday = new Date("December 17, 1995 03:24:00");
birthday = new Date(1995,11,17);
birthday = new Date(1995,11,17,3,24,0);
As you can see, it's pretty simple. Don't complicate, and have a look through the documentation :)
While we're here, here's a test using your example:
var base = new Date("1980-01-01 9:30");
var test = new Date("1980-01-01 9:30:01");
if (test >= base){
alert("test time is newer or equal to base time");
} else {
alert ("test time is older than 9.30");
}
Try this:
var now = new Date();
var hour = now.getHours();
var mintues = now.getMinutes();
if(
(hour*60 + mintues) > 570 &&
hour <= 11
)
{
document.write(now);
}
I don't quite fully understand your question but hope this helps.
c = new Date();
nhour = c.getHours();
nmin = c.getMinutes();
if(nmin <= 9) {
nmin = "0" + nmin;
}
if(nhour <= 9) {
nhour = "0" + nhour;
}
newtime = nhour + "" + nmin;
if(newtime <= 0930){
alert("It is before 9:30am or earlier");
}
I'm using the jonthornton/jquery-timepicker and could not find the hours and minutes selected.
All I could find was a string output of the form '10:30pm'.
Can the hours and minutes be accessed directly from the control?
I imagined you would be able to do this but could not find it.
The best I've been able to do is what follows, anyone got anything better?
$('#StartTime').on('change', function (timeControl) {
var hoursString;
if (timeControl.target.value.indexOf("am") >= 0) {
hoursString = timeControl.target.value.replace("am", ":00 AM");
}
else {
hoursString = timeControl.target.value.replace("pm", ":00 PM");
}
var oneDate = new Date(Date.parse("2000-01-01 " + hoursString));
var minutes = oneDate.getMinutes();
var hours = oneDate.getHours();
console.log("Hours : " + hours + " | Minutes : " + minutes);
});
The long-standing answer would be Moment.js but it is now considered a legacy project in maintenance mode and not recommended for new projects. There are recommendations on their website for replacements, but bringing in a new dependency for this may be overkill.
The value coming in seems to follow a format which we can rely on to make parsing easy.
Format: H:MMxx
Key:
H = hour, 1-2 characters
MM = minutes, always 2 characters
xx = am or pm, always 2 characters
var timeArray = timeControl.split(':');
var meridiem = timeArray[1].substring(2, 4);
var hours = parseInt(timeArray[0]) + (meridiem === 'pm' ? 12 : 0);
var minutes = parseInt(timeArray[1].substring(0, 2));
var seconds = 0;
// Local time zone, read more: https://stackoverflow.com/a/29297375/5988852
var date = new Date();
date.setHours(hours, minutes, seconds);
// If you want UTC instead
utc = Date.UTC(
date.getUTCFullYear(),
date.getUTCMonth(),
date.getUTCDate(),
hours,
minutes,
seconds
);
var date = new Date(utc);
I need help with some Javascript strtotime-type code, please.
Our company runs a weekly promotion for 2 days only for its members. So when a member logs in, they see a banner promoting the promotion. If they happen to login outside of the promotion dates, the banner links to an information page. Otherwise, it links directly to the promotion.
Currently we're updating this by hand each week, which is a pain. We'd like to be able to use Javascript* to automatically change the link for us. OK, no problem, right?
Well, the thing is, what we don't want to have to do is go in and edit the script every week with the specific dates/times -- otherwise, what's the point? Currently the promotion runs Wednesday at 9a.m. to Thursday at 9a.m. It changes from time to time, every couple of months or so (Mon-Tue, 9a-9p, that sort of thing) so we will have to edit the script from time to time, but if we can avoid doing it weekly, that'd be great.
So here's what I came up with. It's heavily commented so my not-so-technical co-workers can go in and make the edits without too much difficulty.
var getData = function(){
var d = new Date();
var today = d.getDay(); // current day, numerically
var hr = d.getHours(); // current hour
// For Days:
// 0 = Sunday
// 1 = Monday
// 2 = Tuesday
// 3 = Wednesday
// 4 = Thursday
// 5 = Friday
// 6 = Saturday
var startDay = 3;
var endDay = 4;
// For Hours:
// This is a 24-hour clock. Midnight (12:00 AM) is 0, Noon = 12, 9 PM = 21, etc.
// So for a start time of 9 AM, put 9, and for an end time of 9 PM, put 21.
var startTime = 12;
var endTime = 15;
// Set the "url" variable to the NON-sale landing page. Put the SALE page URL in
// the "url" variables within the nested "if" statements below:
var url = 'http://link-to-the-non-promo-info-page';
if (( today >= startDay ) && ( hr >= startTime )) {
if ( today <= endDay ) && ( hr <= endTime )) {
url = 'http://link-to-the-live-promotion';
}
}
// ... non-essential variables and the actual display code
// below this line...
// ...
}
Notice I set the vars so that the promo runs 12p-3pm. If this were the real thing, the desired result would be for the promo link to display Wednesday 12pm to Thursday 3pm. What happens with this code, obviously, is that the promo banner is live Wednesday 12-3 and then Thursday 12-3.
I've goofed around with various permutations of the logic and haven't been able to hit the right one. Ultimately, I'd like to be able to open the script (or for one of my co-workers to open it), and be able to set the start day/time and end day/time, without having to set specific dates (Wednesday, July 24 to Thursday, July 25) and it just work.
If this were PHP I'd have it wrapped up. But it's Javascript, so any assistance I can get making this work would be fantastic.
Thanks,
Bob
UPDATE: #Kamala, I tweaked the time a bit by adding minutes, and a few other tweaks, but there's an issue of it not accepting the end time. Note that the script is set so that the start and end day is today, and the start/end times are now past (for EST zone, anyway) but the promo link is still being displayed:
var d = new Date();
var today = d.getDay(); // current day, numerically
var hr = d.getHours(); // current hour
var mn = d.getMinutes();
if (mn < 10) {
mn = "0"+mn;
}
var time = hr+":"+mn;
// For Days:
// 0 = Sunday
// 1 = Monday
// 2 = Tuesday
// 3 = Wednesday
// 4 = Thursday
// 5 = Friday
// 6 = Saturday
var startDay = 5;
var endDay = 5;
// For Hours:
// This is a 24-hour clock. Midnight (12:00 AM) is 0, Noon = 12, 9 PM = 21, etc.
// So for a start time of 9 AM, put 9, and for an end time of 9 PM, put 21.
var startTime = "11:00";
var endTime = "12:00";
// Set the "url" variable to the NON-sale landing page. Put the SALE page URL in
// the "url" variables within the nested "if" statements below:
var url1 = 'http://info-landing-page';
if (( today >= startDay ) && ( today <= endDay ) ) { // Awesome, we're within the promo days
if ( ( today != startDay && today != endDay ) // The promo is in full-swing - doesn't matter what time it is
|| ( today == startDay && time >= startTime )
|| ( today == endDay && time <= endTime ) ) {
url1 = 'http://promo-url';
alert("promo url set");
}
} else {
alert("we're pointing to the LP");
}
Is additional logic needed? Another nested "if" perhaps? I'm lost.
Thanks,
Bob
Try this...
if (( today >= startDay ) && ( today <= endDay ) ) { // Awesome, we're within the promo days
if( ( today != startDay && today != endDay ) // The promo is in full-swing - doesn't matter what time it is
||( today == startDay && hr >= startTime )
|| (today == endDay && hr <= endTime ) )
url = 'http://link-to-the-live-promotion';
}
}
So, what you need are two checks. If the promo's on day 1, is it after a certain time? Or if it's on day 2, is it before a certain time?
if ( today === startDay && hr >== startTime ) {
url = 'http://link-to-the-live-promotion';
} else if ( today === endDay && hr <== endTime ) {
url = 'http://link-to-the-live-promotion';
}
For your problem, there are no days in between the two days.. no need to check if day > startDay && day < endDay.
EDIT: Well, you probably want that capability in case your promo ever goes to 3 days. Here's another try handling this (rewritten to use OR's instead of if-else-if's:
if ((today > startDay && today < endDay) ||
(today == startDay && hr >= startTime) ||
(today == endDay && hr <= endTime)) {
url = 'http://link-to-the-live-promotion';
}
Hey javascript masters,
Attempting to create an age verification page to a client's site. Code below is not functioning as it doesn't matter what year you select, it will still allow you to enter the site. Not sure what I should be looking at to correct.
Any help is appreciated.
<script type="text/javascript"><!--
function checkAge(f){
var dob=new Date();
var date=dob.getDate();
var month=dob.getMonth() + 1;
var year=dob.getFullYear();
var cmbmonth=parseInt(document.getElementById("cmbmonth").options[document.getElementById("cmbmonth").selectedIndex].value);
var cmbday=parseInt(document.getElementById("cmbday").options[document.getElementById("cmbday").selectedIndex].value);
var cmbyear=parseInt(document.getElementById("cmbyear").options[document.getElementById("cmbyear").selectedIndex].value);
age=year-cmbyear;
if(cmbmonth>month){age--;}
else{if(cmbmonth==month && cmbday>=date){age--;}}
if(cmbmonth==0){alert("You must enter the month you were born in.");return false;}
else if(cmbday==0){alert("You must enter the day you were born on.");return false;}
else if(cmbyear==2005){alert("You must enter the year you were born in.");return false;}
else if(age<13){alert("You are unable to view this site!");location.replace("http://www.dharmatalks.org");return false;}
else{return true;}
}
// --></script>
Calculating age in years, months and days is a bit trickier than it should be due to the differences in month and year lengths. Here's a function that will return the difference between two dates in years, months, days, hours, minutes and seconds.
function dateDifference(start, end) {
// Copy date objects so don't modify originals
var s = new Date(+start);
var e = new Date(+end);
var timeDiff, years, months, days, hours, minutes, seconds;
// Get estimate of year difference
years = e.getFullYear() - s.getFullYear();
// Add difference to start, if greater than end, remove one year
// Note start from restored start date as adding and subtracting years
// may not be symetric
s.setFullYear(s.getFullYear() + years);
if (s > e) {
--years;
s = new Date(+start);
s.setFullYear(s.getFullYear() + years);
}
// Get estimate of months
months = e.getMonth() - s.getMonth();
months += months < 0? 12 : 0;
// Add difference to start, adjust if greater
s.setMonth(s.getMonth() + months);
if (s > e) {
--months;
s = new Date(+start);
s.setFullYear(s.getFullYear() + years);
s.setMonth(s.getMonth() + months);
}
// Get remaining time difference, round to next full second
timeDiff = (e - s + 999) / 1e3 | 0;
days = timeDiff / 8.64e4 | 0;
hours = (timeDiff % 8.64e4) / 3.6e3 | 0;
minutes = (timeDiff % 3.6e3) / 6e1 | 0;
seconds = timeDiff % 6e1;
return [years, months, days, hours, minutes, seconds];
}
You can abbreviate the above just after the year part and return just that if you want.
Note that in your code:
var cmbmonth=parseInt(document.getElementById("cmbmonth").options[document.getElementById("cmbmonth").selectedIndex].value);
can be:
var cmbmonth = document.getElementById("cmbmonth").value;
There is no need for parseInt, the Date constructor will happily work with string values. If you have used calendar month numbers for the values (i.e. Jan = 1) then subtract 1 before giving it to the Date constructor, but simpler to use javascript month indexes for the values (i.e. Jan = 0).
You can then do:
var diff = dateDifference(new Date(cmbyear, cmbmonth, cmbdate), new Date());
if (diff[0] < 18) {
// sorry, under 18
}
I'm displaying a message between Saturday at 6pm and Sunday 4am. The last time I had to do this it didn't work because I didn't take into account UTC time going negative when changing it to NYC time.
I am doing the math right (displaying at the appropriate times)?Should I put the UTC conversion code into its own function? Is this the worst js you've ever seen?
-- jquery is called --
$(document).ready(function() {
var dayTime = new Date();
var day = dayTime.getUTCDay();
var hour = dayTime.getUTCHours();
//alert(day.toString()+" "+hour.toString());
if (hour >= 5){
hour = hour-5;
}
else{
hour = hour+19;
if(day > 0){
day--;
}
else{
day = 6;
}
}
//alert(day.toString()+" "+hour.toString());
if ((day == 6 && hour >= 18) || (day == 0 && hour < 4)){
}
else{
$('#warning').hide(); //Want this message to show if js is disabled as well
}
});
Why do you even need that UTC stuff? Just work with local time:
var day = dayTime.getDay();
var hour = dayTime.getHours();
And you can clean up that conditional a bit too:
if (!(day == 6 && hour >= 18) && !(day == 0 && hour < 4)) {
$('#warning').hide();
}
This should get you your server's time:
var dayTime = new Date();
localOffset = dayTime.getTimezoneOffset() * 60000;
serverOffset = 5 * 60 * 60000;
dayTime = new Date(dayTime.getTime() + (localOffset - serverOffset));
Play around with that "5" in the server offset; it's the hours. It may need to be a -5; I'm not really sure.
Also, that's going to break every daylight savings. You'll have to detect that somehow and modify serverOffset.