I at the moment have the day values as strings. (e.g. "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday") but no date.
The days describe opening hours of a shop and I would like to translate these string values dynamically based of the locale set on the shop.
I noticed that JS have the wonderful method Date.prototype.toLocaleDateString() but it doesn't seem like that I can get the localized string without providing a date. How would you go about this?
Have a look at Date.prototype.getDay
// First day of the week depends on the order of this array
const weekdays = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
const date = new Date();
// get first day of week, and then add the weekday
let day = date.getDate() - date.getDay() + weekdays.indexOf(prompt("Day?", "Monday"));
date.setDate(day)
console.log(date.toString());
You can create a dummy date based on the weekday, choosing the year and month such that a day value of 0 matches a Sunday (yes, you can specify the 0th day too).
Then you can use toLocaleDateString with the date to ask for the translated weekday string.
(I also invoked an Intl.DateTimeFormatter here to get the user's default locale, because we cannot specify an options object without also specifying a locale.)
const WEEKDAYS = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']
function translateWeekday (weekdayString) {
const weekdayIndex = WEEKDAYS.indexOf(weekdayString.toLowerCase())
if (weekdayIndex < 0) throw new Error(`Unknown weekday "${weekdayString}"`)
const dummyDate = new Date(2001, 0, weekdayIndex)
const locale = new Intl.DateTimeFormat().resolvedOptions().locale
return dummyDate.toLocaleDateString(locale, { weekday: 'long' })
}
On my machine with German locale, translateWeekday('Wednesday') returns 'Mittwoch' for example.
You can use the Date() perhaps
// current date
let date = new Date();
Additionally, we can get a day of week:
getDay()
Get the day of week, from 0 (Sunday) to 6 (Saturday).
When using the Date() method you can also check for year, month, day and time. Maybe if you want to check so that it´s not on christmas day or after closing hours etc. Should work fine!
Methods:
getFullYear()
Get the year (4 digits)
getMonth()
Get the month, from 0 to 11.
getDate()
Get the day of month, from 1 to 31, the name of the method does look a little bit strange.
getHours(), getMinutes(), getSeconds(), getMilliseconds()
Get the corresponding time components.
Just create a new date object pointing to any Monday, then add days consecutively while calling date.ToLocaleDateString(LOC, {weekday: 'long'}), replace LOC with any locale you wish to use, to define in which language you'd like to get the week names.
function listDayNames(elem, locale)
{
let e = document.getElementById(elem);
let date = new Date('2022/08/22');
for(let i=0;i<=6;i++) {
e.innerHTML += date.toLocaleDateString(locale, { weekday: 'long' }) + '<br>';
date.setDate(date.getDate() + 1);
}
e.innerHTML += '<hr>';
}
let date = new Date();
listDayNames('days', 'en-US');
listDayNames('days', 'de-DE');
<p id="days"></p>
Related
I need a way of getting the name of the day e.g Monday, Tuesday from a date with the format of DD-MM-YYYY
I am using bootstrap datetimepicker and when i select a date, the value is just in the format DD-MM-YYYY, I can't use getDay() because the format doesn't agree with it.
I also can't use new Date() because i has to be a date selected from a calendar. Not todays date.
When I run the following code I get the error:
date.getDay() is not a function.
$('#datepicker').datetimepicker().on('dp.change', function (event) {
let date = $(this).val();
let day = date.getDay();
console.log(day);
});
```
Anyone any ideas?
Parsing string as-is by Date constructor is strongly discouraged, so I would rather recommend to convert your date string into Date the following way:
const dateStr = '15-09-2020',
getWeekday = s => {
const [dd, mm, yyyy] = s.split('-'),
date = new Date(yyyy, mm-1, dd)
return date.toLocaleDateString('en-US', {weekday: 'long'})
}
console.log(getWeekday(dateStr))
function get_day(date){
let d=new Date(date);
let days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
let day_index=d.getDay();
return days[day_index]
}
let today=new Date();
console.log("today is",get_day(today))
I am looking to do something quite complex and I've been using moment.js or countdown.js to try and solve this, but I think my requirements are too complex? I may be wrong. Here is the criteria...
I need to be able to have the following achievable without having to change the dates manually each year, only add it once and have many countdowns on one page.
Find current date
Find current year
Find current month
Find day within week of month that applies
¬ 3rd Sunday or 2nd Saturday
Convert to JS and output as html and run countdown
When past date - reset for following year
Pretty mental. So for example if an event is always on the 3rd Sunday of March. The date would not be the same each year.
2016 - Sunday March 19th
2017 - Sunday March 20th
2018 - Sunday March 18th etc.
I hope this is explained well, I realise it may be a total mess though. I managed to get it resetting each year with the date added manually but then someone threw in the spanner of the date being different each year.
var event = new Date();
event = new Date(event.getFullYear() + 1, 3 - 1, 19);
jQuery('#dateEvent').countdown({ until: event });
<div id="dateEvent"></div>
I have edited this answer as I have now put together a solution that works for me. As I believe this isn't simple coding due to the fact it wasn't actually answered 'Please, this is basic coding. pick up a javascript book and learn to code', yeah thanks...
// get the specific day of the week in the month in the year
function getDay(month) {
// Convert date to moment (month 0-11)
var myMonth = moment("April", "MMMM");
// Get first Sunday of the first week of the month
var getDay = myMonth.weekday(0); // sunday is 0
var nWeeks = 3; // 0 is 1st week
// Check if first Sunday is in the given month
if (getDay.month() != month) {
nWeeks++;
}
// Return 3rd Sunday of the month formatted (custom format)
return getDay.add(nWeeks, 'weeks').format("Y-MM-D h:mm:ss");
}
// print out the date as HTML and wrap in span
document.getElementById("day").innerHTML = '<span>' + getDay() + '</span>';
Using
<script src="moment.js"></script>
Hope it helps someone - I'll update when I figure how to + 1 year after it's checked current date and event has passed. I'll look in that JS book.
Please take a look at the below code, I explained in the comment what what does.
You use it by supplying a javascript Date object of any wished start date, and then add as a second value the corresponding year you wish to know the date in.
var date = new Date("2016-03-20");
function getDayInYear(startDate, year) {
// get a moment instance of the start date
var start = moment(startDate);
// collect the moment.js values for the day and month
var day = start.day();
var month = start.month();
// calculate which week in the month the date is.
var nthWeekOfMoth = Math.ceil(start.date() / 7);
// Build up the new moment with a date object, passing the requested year, month and week in it
var newMoment = moment(new Date(year,month,(nthWeekOfMoth * 7)));
// Return the next instance of the requested day from the current newMoment date value.
return newMoment.day(day);
}
var oldMoment = moment(date);
var newMoment2017 = getDayInYear(date,2017);
var newMoment2018 = getDayInYear(date,2018);
console.log(oldMoment.format('YYYY MMMM dddd DD'));
console.log(newMoment2017.format('YYYY MMMM dddd DD'));
console.log(newMoment2018.format('YYYY MMMM dddd DD'));
/** working from today up to 10 years into the future **/
var date = new Date();
var year = date.getFullYear();
for(var i = 0; i < 11; i++) {
console.log(getDayInYear(date, year+i).format('YYYY MMMM dddd DD'));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.js"></script>
This question already has answers here:
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 8 years ago.
how can I get this format in javascript:
Saturday,September 21,2013
I did this
var date= new Date();
var d= date.getDate();
but all I am getting is 21 wish is the number of the day
I'd suggest you to use a Moment.js library to effectively work with date and time in JavaScript.
var date,
dateString;
date = new Date();
dateString = moment(date).format('dddd, MMMM, DD, YYYY');
DEMO
You can use the following methods:
var d = new Date();
d.getDate() // returns the number of the day
d.getMonth() // returns the number of the month (starting from 0)
d.getDay() // returns the number of the day in the week
d.getFullYear() // returns the full year, i.e. 2013
In order to use month and day names you can easily write a convertion function:
function nameOfDay(dayNumber) {
return [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'
][dayNumber];
}
and a similar one for the months.
(or maybe, if that functionality is very used in your application, you can use an extern library like datejs or Moment.js)
Is it possible to get next date of a given date in "yyyymmdd" format with default java script or jquery functions?
As you've specified jQuery UI you can use its built-in date formatter to get the required output.
The use of the regexp and new Date shown below is to guarantee that the vagaries of date parsing don't affect the result.
function getTomorrow(dateStr) {
var ymd = dateStr.match(/^(\d{4})(\d{2})(\d{2})$/);
if (ymd) {
var date = new Date(ymd[1], ymd[2] - 1, ymd[3]);
date.setDate(date.getDate() + 1);
return $.datepicker.formatDate('yymmdd', date);
} else { // parse error
return null;
}
}
Demo at http://jsfiddle.net/alnitak/R8awH/
There seems to be a bit of confusion here.
At the heart of a javascript Date object is the milliseconds since 1970-01-01 00:00:00 UTC. That last bit is very important.
If you create a date by specifying the parts, e.g. for 2 September 2012 (note month number):
new Date(2012, 8, 2);
then a date object is created for midnight at the start of the date in the local time zone of the host, i.e. 2012-09-02T00:00:00 in the local timezone. However, if you specify a time since epoch, e.g.
new Date(1346544000000) // 2012-09-02T00:00:00Z
then the date is created at that time UTC, so it will show a different local time in different timezones that represents the same time UTC. So if the time is 2012-09-02T00:00:00Z, then in a timezone ten hours ahead of GMT (GMT+10) it will be:
2012-09-02T10:00:00+1000
If the timezone is six hours behind GMT (GMT-06) it will be:
2012-09-01T18:00:00-0600
and so on.
Construct the date object, and set the date plus 1.
var dateStr = "20120902";
var d = new Date(dateStr.replace(/(\d{4})(\d{2})(\d{2})/, '$1/$2/$3'));
d.setDate(d.getDate() + 1);
console.log(d);
Here is your code:
function getnextDay(prevDate) {
var weekday = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
prevDate = prevDate.toString();
var formatteDate = prevDate.substr(0, 4) + ',' + prevDate.substr(4, 2) + ',' + prevDate.substr(6, 2);
formatteDate = new Date(formatteDate);
document.write(weekday[formatteDate.getDay() + 1])
}
getnextDay(19890831)
and
FIDDLE
Its pretty straight forward.
var today = new Date();
var date = new Date(today.getFullYear(),today.getMonth(),today.getDate()+1);
Use moment.js if you extensively use date functionalities.
For just getting the next day, this would suffice.
yes
It is pretty much easy with javaScript as follow:
today = new Date().getTime();
tomorrow = today + 24*60*60*1000;
parsed_tomorrow = new Date(tomorrow);
How can I create a date object which is less than n number of months from another date object? I am looking for something like DateAdd().
Example:
var objCurrentDate = new Date();
Now using objCurrentDate, how can I create a Date object having a date which is six months older than today's date / objCurrentDate?
You can implement very easily an "addMonths" function:
function addMonths(date, months) {
date.setMonth(date.getMonth() + months);
return date;
}
addMonths(new Date(), -6); // six months before now
// Thu Apr 30 2009 01:22:46 GMT-0600
addMonths(new Date(), -12); // a year before now
// Thu Oct 30 2008 01:20:22 GMT-0600
EDIT: As reported by #Brien, there were several problems with the above approach. It wasn't handling correctly the dates where, for example, the original day in the input date is higher than the number of days in the target month.
Another thing I disliked is that the function was mutating the input Date object.
Here's a better implementation handling the edge cases of the end of months and this one doesn't cause any side-effects in the input date supplied:
const getDaysInMonth = (year, month) => new Date(year, month, 0).getDate()
const addMonths = (input, months) => {
const date = new Date(input)
date.setDate(1)
date.setMonth(date.getMonth() + months)
date.setDate(Math.min(input.getDate(), getDaysInMonth(date.getFullYear(), date.getMonth()+1)))
return date
}
console.log(addMonths(new Date('2020-01-31T00:00:00'), -6))
// "2019-07-31T06:00:00.000Z"
console.log(addMonths(new Date('2020-01-31T00:00:00'), 1))
// "2020-02-29T06:00:00.000Z"
console.log(addMonths(new Date('2020-05-31T00:00:00'), -6))
// "2019-11-30T06:00:00.000Z"
console.log(addMonths(new Date('2020-02-29T00:00:00'), -12))
// "2019-02-28T06:00:00.000Z"
Create date object and pass the value of n, where n is number(add/sub) of month.
var dateObj = new Date();
var requiredDate= dateObj.setMonth(dateObj.getMonth() - n);
var oldDate:Date = new Date();
/*
Check and adjust the date -
At the least, make sure that the getDate() returns a
valid date for the calculated month and year.
If it's not valid, change the date as per your needs.
You might want to reset it to 1st day of the month/last day of the month
or change the month and set it to 1st day of next month or whatever.
*/
if(oldDate.getMonth() < n)
oldDate.setFullYear(oldDate.getFullYear() - 1);
oldDate.setMonth((oldDate.getMonth() + n) % 12);
You have to be careful because dates have a lot of edge cases. For example, merely changing the month back by 6 doesn't account for the differing number of days in each month. For example, if you run a function like:
function addMonths(date, months) {
date.setMonth((date.getMonth() + months) % 12);
return date;
}
addMonths(new Date(2020, 7, 31), -6); //months are 0 based so 7 = August
The resulting date to return would be February 31st, 2020. You need to account for differences in the number of days in a month. Other answers have suggested this in various ways, by moving it to the first of the month, or the last of the month, or the first of the next month, etc. Another way to handle it is to keep the date if it is valid, or to move it to the end of the month if it overflows the month's regular dates. You could write this like:
function addMonths(date, months) {
var month = (date.getMonth() + months) % 12;
//create a new Date object that gets the last day of the desired month
var last = new Date(date.getFullYear(), month + 1, 0);
//compare dates and set appropriately
if (date.getDate() <= last.getDate()) {
date.setMonth(month);
}
else {
date.setMonth(month, last.getDate());
}
return date;
}
This at least ensures that the selected day won't "overflow" the month that it is being moved to. Finding the last day of the month with the datePart = 0 method is documented here.
This function still leaves a lot to be desired, as it doesn't add years and you can't subtract more than a year (or you will run into a new issue with negatives being involved). However, fixing those and the other issues you may run into (namely timezones) will be left as an exercise for the reader.