How can I show current full date in the title of jquery datepicker like this :
05 July 2015 because it show me just July 2015
You could use a function like this in onSelect
function showDateInTitle(picker) {
var span = picker.dpDiv[0].querySelector('.ui-datepicker-day'),
df, month;
if (span === null) {
month = picker.dpDiv[0].querySelector('.ui-datepicker-month');
if (!month) return;
span = document.createElement('span');
span.setAttribute('class', 'ui-datepicker-day');
df = document.createDocumentFragment();
df.appendChild(span);
df.appendChild(document.createTextNode('\u00a0'));
month.parentNode.insertBefore(
df,
month
);
}
span.textContent = picker.selectedDay;
}
Still looking through API for a handler for after the datepicker is shown before choice is made
You can implement an afterShow as described here with a slight modification to get the instance
$(function() {
$.datepicker._updateDatepicker_original = $.datepicker._updateDatepicker;
$.datepicker._updateDatepicker = function(inst) {
$.datepicker._updateDatepicker_original(inst);
var afterShow = this._get(inst, 'afterShow');
if (afterShow)
afterShow.apply((inst.input ? inst.input[0] : null), [inst]);
}
});
Now DEMO
I couldn't find a non-hacky way of doing it, but changing the defaults config to the text you want to show might do it for you:
var defaults = {
monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ]
};
var today = new Date();
var month = today.getMonth();
defaults.monthNames[month] = today.getDate() + ' ' + defaults.monthNames[month];
$.datepicker.setDefaults(defaults);
Here is a working plnkr: http://plnkr.co/edit/gfp95VOchd4fhQOktIL3?p=preview
Here is my solution, it is a simple jquery solution that append the day value to the current datepicker widget.
$('#datepicker').click(function(){
var $datePickerBox = $('#ui-datepicker-div');
//var $datePickerBox = $(this).closest('.ui-datepicker.ui-widget');
var $monthName = $datePickerBox.find('.ui-datepicker-month');
var currentDay = '';
if($(this).val().trim().length==0){
currentDay = $datePickerBox.find('.ui-datepicker-today').text();
} else {
currentDay = $datePickerBox.find('.ui-datepicker-current-day').text();
}
$monthName.text( currentDay + " " + $monthName.text() );
});
Code pen link
http://codepen.io/anon/pen/WvzKJo
If you want to always show the current date at the top and not the selected date, using #PaulS.'s code change
span.textContent = picker.selectedDay;
to
span.textContent = new Date().getDate();
Demo
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 need help in getting the last 3 months in javascript. I have generated an excel sheet in which the user has to populate month number in month column and year in year column.
I need to validate that the user has entered correct month and year combination based on current year.
User fill up the excel and upload it to node js fastify server. After that, I need to validate the month and year.
example:
If the current year is 2018 and the month is Jan(1). Users can enter 2017 in a year and 10 in a month.
The current year is 2019 and the month is 10. User can enter 8 in month
Please guide me. How can I achieve this?
const months = ['January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'];
const getLastThreeMonths = () => {
const now = new Date();
const previousMonths = [];
for (let i = 0; i < 3; i += 1) {
previousMonths.push(`${months[(now.getMonth() - i)]}`);
}
return previousMonths;
};
console.log(getLastThreeMonths());
one working code sample is here ..You can change the content as per your requirement.
$(document).ready(function () {
var date = new Date();
var month = date.getMonth() + 1;
var year = date.getFullYear();
if (month == "1") {
year = date.getFullYear() - 1;
}
month = month - 2;
$("#month").on('change', function () {
if ($("#month").val() != month) { alert("not valid month"); }
});
$("#year").on('change', function () {
if ($("#year").val() != year) {alert("not valid year"); }
});
});
<input type="text" id="month" placeholder="put month here"/>
<input type="text" id="year" placeholder="put year here"/>
My Answer:
const dateValidator = (month, year) => {
const allowedRange = [];
for (let i = 1; i <= 3; i += 1) {
const current = new Date();
current.setMonth(current.getMonth() - i + 1);
allowedRange.push({ month: current.getMonth() + 1, year: current.getFullYear() });
}
return allowedRange.find(ar => ar.month === month && ar.year === year);
};
Good day,
I've been using the following time function JS in an HTML code. I'm still in the progress of learning and understanding JS and been playing around with it. However, I recently noticed that whenever my minutes are less than 10, the 0 is taken away, say 14:5 instead of 14:05. Is there quick format way to fix this?
Thanks in advance, here's the JS function
function updateClock() {
var now = new Date(),
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
time = now.getHours() + ':' + now.getMinutes();
date = [now.getDate(),
months[now.getMonth()],
now.getFullYear()].join(' ');
// set the content of the element with the ID time to the formatted string
// document.getElementById('time').innerHTML = [date, time].join(' ');
document.getElementById('time').innerHTML = ["Today is", date, "and the time is", time].join(' ');
setTimeout(updateClock, 1000);
}
updateClock();
You should be able to check if your minutes value is less than 10 and append a 0 to the front of it :
// If the minutes are greater than 10, pad them with a '0'
time = now.getHours() + ':' + (now.getMinutes() < 10 ? '0' : '') + now.getMinutes();
Example
You can see a working example here and demonstrated below :
As far as I know, there is no built-in method for this. However, you can use a ternary operator to add the 0 when necessary.
var mins = now.getMinutes();
var minsFixed = mins < 10 ? '0' : '' + mins;
time = now.getHours() + ':' + minsFixed;
Just use one more format function like this and call it everywhere:
function zero(num) {
return num < 10 ? '0' + num : num;
}
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
function tolocal(str)
{
var date, split, dSplit, tSplit, d, raw;
date = '';
split = str.split(' ');
if (split.length === 2) {
dSplit = split[0].split('-');
tSplit = split[1].split(':');
}
raw = d.toLocaleString().split(' GMT')[0];
return raw.substring(raw.indexOf(", ")+2, raw.lastIndexOf(':')) + " " + raw.substring(raw.length-2,raw.length)
}
The above code, works well in ie browser where I get the output in the following format.
November 13,2012 10:15 AM
But I am not able to achieve the same in the chrome browser. Is there any other function which will help me achieve the same output? date.toUTCString() provides the same result but I am not sure how different it is to toLocaleString() in terms of functionality.
Thanks in advance.
Just do it manually:
// Where "date" is a Date object
function dateFormatUTC(date) {
var months = [
'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'
];
var hours = date.getUTCHours();
if (hours < 10) hours = '0' + hours;
var minutes = date.getUTCMinutes();
if (hours < 10) hours = '0' + hours;
var monthName = months[date.getUTCMonth()];
var timeOfDay = hours < 12 ? 'AM' : 'PM';
return monthName + ' ' + date.getUTCDate() + ', ' +
date.getUTCFullYear() + ' ' + hours + ':' + minutes + timeOfDay;
}
maybe you can use a thirdparty library to do stuff like that: moment.js is a good one.
Example:
moment(d).format('MMMM Do, YYYY h:mms a');
you can try using options like below:
var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
// request a weekday along with a long date
var options = {weekday: "long", year: "numeric", month: "long", day: "numeric"};
// an application may want to use UTC and make that visible
options.timeZone = "UTC";
options.timeZoneName = "short";
alert(date.toLocaleString("en-US", options));
Please find the reference #
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString