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))
Related
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>
I have a form that sends the value of year and months from an input and then while sending the value to the server I am converting that values to ISO string like that:
const toIsoString = (year, month, day) => moment(new Date(year, month - 1, day)).toISOString(true).split('.')[0];
And then in the values I am using it like this.
StartDate: toIsoString(data.StartYear, parseInt(data.StartMonth, 10), 1),
In that case It is sending the value like this:
startDate: "2021-01-01T00:00:00"
Does anybody know why the Time period is being ignored and how can I also send the time period with the year, month and date values.Any helps would be highly appreciated.Thanks...
Does anybody know why the Time period is being ignored and how can I also send the time period with the year, month and date values.Any helps would be highly appreciated.
The time isn't ignored. In the function:
const toIsoString = (year, month, day) =>
moment(new Date(year, month - 1, day)).toISOString(true).split('.')[0];
the values for hour, minute, second and millisecond are omitted so they default to 0. What time are you expecting?
If you want the current local time added to the date, then create a date and set the year, month and day to the required values without modifying the time (though I don't know why you'd want to do that).
Rather than creating a string that you then need to further process, tell moment.js the format you want:
function toIsoString (year, month, day) {
return moment(new Date().setFullYear(year, month-1, day)).format('YYYY-MM-DD HH:mm:ss');
}
console.log(toIsoString('2021','1','1'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script>
You can also do that without a library, see How to format a JavaScript date, e.g.:
function formatDate(year, month, date) {
let z = n => (n<10?'0':'') + Number(n);
return `${year}-${z(month)}-${z(date)} ${
new Date().toLocaleString('en',{
hour12:false,
hour:'2-digit',
minute:'2-digit',
second:'2-digit'})
}`;
}
console.log(formatDate('2021','1','01'))
Its because you are only setting year, month and date while creating moment object. You are not setting time
You should do something like
const toIsoString = (year, month, day) => {
const currDate = moment(new Date());
currDate.year(year);
currDate.month(month - 1);
currDate.date(day);
return currDate.toISOString(true).split('.')[0];
}
Or simply use set function
const toIsoString = (year, month, day) => {
const currDate = moment(new Date());
currDate.set({
'year': year,
'month': (month - 1),
'date': day
});
return currDate.toISOString(true).split('.')[0];
}
How to convert a date(01-02-2019) to Wed, 02 Jan 2019 in javascript?
$(document).ready(function () {
var dealDate = 01-02-2019;
});
Just use new Date() on that date value:
$(document).ready(function() {
var dealDate = '01-02-2019';
//replace all - to / to make it work on firefox
dealDate = dealDate.replace(/-/g,'/');
alert(new Date(dealDate).toDateString())
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You can use Date Constructor and Date.prototype.toDateString():
The toDateString() method returns the date portion of a Date object in human readable form in American English.
$(document).ready(function () {
var dealDate = new Date('01-02-2019').toDateString();
console.log(dealDate);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You can split your string on - and then generate the date using Date constructor.
var dealDate = '01-02-2019';
let [month, day, year] = dealDate.split('-').map(Number);
let date = new Date(year, month - 1, day);
console.log(date.toDateString());
TO convert the date to in the format of month day, month day number and year use the below jquery. It will convert the current date to the exact format you asked for
$(document).ready(function() {
var dealDate = new Date();
alert(dealDate.toUTCString());
});
your expected format is like [day][comma][date][month][year]. I split toDateString() and rearranged in expected format.
function formatedDate(d){
var dt=new Date(d).toDateString().split(' ');
return dt[0]+', '+dt[2]+' '+dt[1]+' '+dt[3]; //[Day][comma][date][month][year]
}
console.log(formatedDate('01-02-2019'))
I have a date fomatted as dd/mm/yyyy format, how can I format as mm/dd/yyyy.
var date = '23/03/2015';
var dateSplit = date.split('/');
var newDate = dateSplit[1]+'/'+dateSplit[0]+'/'+dateSplit[2];
This is the simplest solution which I have in mind, but it's not the best one, because it works only for the format which you gave. For more general solution I'd parse the date to Date() object and then use the methods to extract the required information
As I understand, you have a string format date?
Just use simple regex replace.
var toFormat = 'dd/mm/yyyy';
var formated = toFormat.replace(/(..)\/(..)\/(....)/, "$2/$1/$3");
// formated is now 'mm/dd/yyyy'
However this is a hackish way to do stuff. You might want to use a library such as moment.js if you require more datetime manipulation
As an universal solution, you can combine the 3 main functions of Date to get desired string. It will work for any kind of date format input.
getDate() // To get date
getMonth() // To get month
getFullYear() // To get year
You may want to do following:
<script type="text/javascript">
var date = new Date();
var curr_date = date.getDate();
var curr_month = date.getMonth() + 1; // months are zero based
var curr_year = date.getFullYear();
document.write(curr_month + "/" + curr_date + "/" + curr_year);
</script>
Get more insight of it.
I would use http://momentjs.com/
moment().format('MMMM Do YYYY, h:mm:ss a'); // April 15th 2015, 3:03:45 pm
moment().format('dddd'); // Wednesday
moment().format("MMM Do YY"); // Apr 15th 15
moment().format('YYYY [escaped] YYYY'); // 2015 escaped 2015
moment().format(); // 2015-04-15T15:03:45+03:00
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)