I'm trying to find the actual position of a weekday in constant time. I get it working with loop but trying to find out it with some Mathematics. I know it is like divide it by 7 but not getting it work.
Here is the code.
for(var ind=0; ind<=between.length; ind++){
if (new Date(between[ind]).getMonthWeek() === baseDtWk && new Date(between[ind]).getDay() === baseDtD) {
datesToBeMarked.push(between[ind]);
console.log(" :Date: " + between[ind] + " :Week: " + new Date(between[ind]).getMonthWeek());
console.log("Date entered : " + new Date(between[ind]));
}
}
I have done this few days back. It is as simple as the code below. :)
On fiddle.
Number.prototype.nth= function(){
var n= Math.round(this), t= Math.abs(n%100), i= t%10;
if(i<4 && (t<4 || t> 20)){
switch(i){
case 1:return n+'st';
case 2:return n+'nd';
case 3:return n+'rd';
}
}
return n+'th';
}
Date.prototype.nthofMonth= function(){
var today= this.getDate(),m=this.getMonth(),
day= ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday',
'Friday', 'Saturday'][this.getDay()],
month= ['January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'][m];
return [(m+1)+'-'+today,'the ', Math.ceil(today/7).nth(), day, 'of', month, 'in', this.getFullYear()].join(' ');
}
var date=new Date().nthofMonth();
console.log(date);
You haven't shown how you want the result to look, I guess you want to know if a particular date is, say, the nth Tuesday, e.g.
// Add ordinal to a number
function addOrdinal(n) {
var ord = [,'st','nd','rd'];
var a = n % 100;
return n + (ord[a>20? a%10 : a] || 'th');
}
// Return the ordinal number of a day in the month
function ordinalDay(d) {
d = d || new Date();
var days = ['Sunday','Monday','Tuesday','Wednesday',
'Thursday', 'Friday','Saturday'];
return addOrdinal(Math.ceil(d.getDate()/7)) + ' ' + days[d.getDay()];
}
console.log(ordinalDay(new Date(2015,0,1))); // 1st Thursday
console.log(ordinalDay(new Date(2015,0,27))); // 4th Tuesday
console.log(ordinalDay(new Date(2015,0,31))); // 5th Saturday
console.log(ordinalDay(new Date(2015,11,25))); // 4th Friday
Related
I am building a weather app using HTML, CSS and JavaScript.
I have succeed in displaying my current time but no luck displaying local time of the input city.
here is what it looks like:
Can I perhaps us getTimeZoneOffset() somewhere? I don't seem to figure out
function displaytheResults (weather) {
let now = new Date();
let date = document.querySelector('.location .date')
date.innerText = dateBuilder(now);
}
function dateBuilder(dt) {
let months = ['January', 'Febuary', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
let days = ['Monday', 'Tuesday', 'Wednesday','Thursday', 'Friday', 'Saturday']
let date = dt.getDate();
let year = dt.getFullYear();
let day = days[dt.getDay()];
let month = months[dt.getMonth()]
return `${day} ${date} ${month} ${year}`;
}
Once you have the offset value, pass it into this function, in order to get the time in the desired city:
function dateBuilder(city, offset) {
var date = new Date();
var utc = date.getTime() + (date.getTimezoneOffset() * 60000);
var newDate = new Date(utc + (3600000 * offset));
return `The local time in ${city} is ${newDate.toLocaleString()}`
}
I have a perfectly functioning clock.js widget that I'm using to display date and time on multiple displays throughout our offices in several states.
The offices in the Eastern timezone have no issue, as this defaults to eastern time (our server running the screens for every display is eastern).
However, I want to add a conditional in here (say if $screenID == 3 {... so that on the screens in the Central time zone it shows the proper central time.
How should I go about adding a block in here for that condition to show central rather than eastern?
function startTime() {
var today = new Date();
var hr = today.getHours();
var min = today.getMinutes();
// var sec = today.getSeconds();
ap = (hr < 12) ? "<span>AM</span>" : "<span>PM</span>";
hr = (hr == 0) ? 12 : hr;
hr = (hr > 12) ? hr - 12 : hr;
//Add a zero in front of numbers<10
hr = checkTime(hr);
min = checkTime(min);
// sec = checkTime(sec);
document.getElementById("clock").innerHTML = hr + ":" + min + " " + ap;
var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var curWeekDay = days[today.getDay()];
var curDay = today.getDate();
var curMonth = months[today.getMonth()];
// var curYear = today.getFullYear();
var date = curWeekDay+", "+curDay+" "+curMonth;
document.getElementById("date").innerHTML = date;
var time = setTimeout(function(){ startTime() }, 500);
}
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
Use timezones.
function startTime(screen, loc) {
var timeZone = "America/Chicago";
if (screen === 1)
timeZone = "America/New_York";
var dateOptions = { weekday: 'long', day: 'numeric', month: 'long', timeZone: timeZone };
var timeOptions = { hour: 'numeric', minute: 'numeric', timeZone: timeZone };
var dt = new Date();
document.getElementById("myclock" + loc).innerHTML = dt.toLocaleString("en-US", timeOptions);
document.getElementById("mydate" + loc).innerHTML = dt.toLocaleString("en-NZ", dateOptions);
}
startTime(0, 1);
startTime(1, 2);
<div id="myclock1">asdf</div>
<div id="mydate1">asdf</div>
<hr>
<div id="myclock2">asdf</div>
<div id="mydate2">asdf</div>
Is there a way I can have a fixed date that I will use for conversion.
as you can see, the code below states that it is the time in Manila, PH but when you open it given that you are in a different timezone to me it will give you different time. Date(); will just get the time in your computer.
Is there a way to get a date which will be use as a default date so that I can add or minus hours to get my desired conversion date even though it will be open in different timezones?
function showTime() {
var a_p = "";
var today = new Date();
var curr_hour = today.getHours();
var curr_minute = today.getMinutes();
var curr_second = today.getSeconds();
var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var myDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var date = new Date();
var day = date.getDate();
var month = date.getMonth();
var thisDay = date.getDay(),
thisDay = myDays[thisDay];
var yy = date.getYear();
var year = (yy < 1000) ? yy + 1900 : yy;
if (curr_hour < 12) {
a_p = "<span>AM</span>";
} else {
a_p = "<span>PM</span>";
}
if (curr_hour == 0) {
curr_hour = 12;
}
if (curr_hour > 12) {
curr_hour = curr_hour - 12;
}
curr_hour = checkTime(curr_hour);
curr_minute = checkTime(curr_minute);
curr_second = checkTime(curr_second);
document.getElementById('clock-large1').innerHTML=curr_hour + " : " + curr_minute + " : " + curr_second + " " + a_p;
document.getElementById('date-large1').innerHTML="<b>" + thisDay + "</b>, " + day + " " + months[month] + " " + year;
}
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
setInterval(showTime, 500);
<div id="clockdate-full">
<div class="wrapper-clockdate1">
<div id="clock-large1"></div>
<div id="date-large1"></div>
<div id="timezone">Manila, PH</div>
</div>
</div>
Checkout moment .js
http://momentjs.com
You can specify the time zone of the date time
var timezone = 'America/Chicago'
moment().tz(timezone).format('hh:mm:ss z')
If you can't use an external link, you should try the code below:
var opt= {
timeZone: 'America/Chicago',
year: 'numeric', month: 'numeric', day: 'numeric',
hour: 'numeric', minute: 'numeric', second: 'numeric'
},
formatDate = new Intl.DateTimeFormat([], opt)
formatDate.format(new Date())
Is there a way to get a date which will be use as a default date so that I can add or minus hours to get my desired conversion date even though it will be open in different timezones?
Yes, just specify the "fixed" date in a suitable format. Most browsers will parse ISO 8601 extended format strings like 2017-05-25T17:35:48+08:00. That represents 5:30pm in Manilla, which is UTC+08:00.
To get the equivalent time on the user's system:
var d = new Date('2017-05-25T17:35:48+08:00');
console.log(d.toString()); // equivalent local time
If you want to support browsers like IE 8, you'll need to parse the string manually or use a library with a parser, e.g. moment.js or fecha.js.
This question already has answers here:
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 9 years ago.
How would I format a date in javascript in the format: June 2, 2013, 1:05 p.m.
Here is a relevant link, but I'm still having trouble getting this exact formatting, based on Date(). http://www.webdevelopersnotes.com/tips/html/10_ways_to_format_time_and_date_using_javascript.php3
Why not write a function to get bits of the date for you and return an Object which lets you build a string as easily as string concatenation of Object properties.
The example below will always base answer on UTC time
var easyDate = (function () {
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
thstndrd = ['th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th'];
return function (d) {
var dow = d.getUTCDay(),
dom = d.getUTCDate(),
moy = d.getUTCMonth(),
y = d.getUTCFullYear(),
h = d.getUTCHours(),
m = d.getUTCMinutes(),
s = d.getUTCSeconds();
return {
dom: '' + dom,
th: thstndrd[dom % 10],
day: days[dow],
moy: '' + (moy + 1),
month: months[moy],
year: '' + y,
ampm: h < 12 ? 'a.m.' : 'p.m.',
hh: h < 10 ? '0' + h : '' + h,
sh: '' + (h % 12 || 12),
mm: m < 10 ? '0' + m : '' + m,
ss: s < 10 ? '0' + s : '' + s,
};
};
}());
var o = easyDate(new Date());
// Object {dom: "2", th: "nd", day: "Sunday", moy: "6", month: "June"…}
o.month + ' ' + o.dom + ', ' + o.sh + ':' + o.mm + ' ' + o.ampm;
// "June 2, 8:43 p.m."
This should be useful to you: http://blog.stevenlevithan.com/archives/date-time-format
i would suggest moment.js. here it is: http://momentjs.com/
import it and do this
moment().format('LLL');
this is what you want
At w3schools you can find a complete reference to Javascript's Date object
Then you can use the methods to combine into a string of your liking.
var d = new Date();
d.getHours() + ":" + ...
There isn't a method to get the month name, you will need to get the number and create a switch.
The hour is in 24h format, so you have to convert and calculate if it is am or pm.
The day and year you can get directly using getDate() and getFullYear()
References
w3schools
MDN
Say I'm given a date, from which I can get its day of the month and day of the week. For example (in Javascript):
var d = new Date(1316038581772); // Wed Sep 14 2011 12:16:21 GMT-1000
var dayOfWeek = d.getDay(); // 3 - Wednesday
var dayOfMonth = d.getDate(); // 14 - Day of month
I'm looking for a value n such that this date is the nth day of the week in the month. In this case, I'm looking for n=2, for the 2nd Wednesday in September 2011.
The naive algorithm would be to find the first occurrence of that weekday in the month, take the difference in days, and divide by 7, but this isn't in constant time. For example, I would need to iterate over each day from the first day in September 7 times to reach the first Wednesday.
Is there a constant-time solution to this problem?
(For anyone interested, I'm trying to generate ordinal values for iCalendar recurrence rules; given a date, generate the monthly recurrence for the nth day of each month. The rule for this case would be something like
RRULE:FREQ=MONTHLY;INTERVAL=1;BYDAY=WE;BYSETPOS=2
or
RRULE:FREQ=MONTHLY;INTERVAL=1;BYDAY=2WE
)
Divide by 7 and round up.
The 14th is always the 2nd [weekday] of the month, the 15th is always the 3rd [weekday] of the month, etc.
Take the day of the month, add 6, and divide by 7, throwing away the remainder.
You need two functions- one to get the day info, the other for the nth.
Number.prototype.nth= function(){
var n= Math.round(this), t= Math.abs(n%100), i= t%10;
if(i<4 && (t<4 || t> 20)){
switch(i){
case 1:return n+'st';
case 2:return n+'nd';
case 3:return n+'rd';
}
}
return n+'th';
}
Date.prototype.nthofMonth= function(){
var today= this.getDate(),m=this.getMonth(),
day= ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday',
'Friday', 'Saturday'][this.getDay()],
month= ['January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'][m];
return [(m+1)+'-'+today,'the ', (Math.ceil((today)/7)).nth(), day, 'of', month, 'in', this.getFullYear()].join(' ');
}