getting a specific dateformat in javascript [duplicate] - javascript

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)

Related

Javascript get localized weekday without a DateTime object

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>

Date formatter inside DIV tag [duplicate]

This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 7 months ago.
<div>
<strong>Date: </strong>
${dateInUtc}
</div>
This dateInUtc (2021-12-09T15:43:29+01:00) contains the date in UTC format.
Need to format it like this 2021-12-09 - 15:43:29.
How do achieve this without using external libraries?
Because the required format is close to what you already have you can do this quite simply without having to parse the date in the first place.
const dateInUtc = `2021-12-09T15:43:29+01:00`;
const formattedDate = dateInUtc.replace(`T`, ` - `).split(`+`)[0];
console.log(formattedDate);
If you are using any framework then use Datapipe in that framework.
Example: Datepipe-Angular
If you are not using any framework then use the date format utility function like:
df = (function(d) {
d = new Date(d);
return `${d.getFullYear()}-${(d.getMonth()+1).toString().replace(/^[0-9]$/g, '0$&')}-${(d.getDate()).toString().replace(/^[0-9]$/g, '0$&')} - ${(d.getHours()).toString().replace(/^[0-9]$/g, '0$&')}:${(d.getMinutes()).toString().replace(/^[0-9]$/g, '0$&')}:${(d.getSeconds()).toString().replace(/^[0-9]$/g, '0$&')}`;
});
console.log(df(new Date().toUTCString()));
Output:
'2022-07-22 - 14:41:36'
Explanation:
This is the objective to get data from the Date object.
d = new Date(d);
obj = {
date: d.getDate(),
month: d.getMonth(),
year: d.getFullYear(),
hour: d.getHours(),
minute: d.getMinutes(),
second: d.getSeconds()
}
I am using regular expression str.replace(/^[0-9]$/g, '0$&') or str.replace(/^[0-9]{1}$/g, '0$&')to add an addition zero if data is a single digit.
Like:
'0'.replace(/^[0-9]$/g, '0$&') // '00'
'8'.replace(/^[0-9]$/g, '0$&') // '08'
'12'.replace(/^[0-9]$/g, '0$&') //'12'

Is there a way to set date and month on a date object in a single statement?

I'm trying to calculate a date based on another date by adding a certain period of time. Let's say if I want to add 3 months to a date, then the new date should be one day before the date after 3 months. Taking that example, below is the code that I came closest to for achieving what I want to do:
new Date(
date
.setMonth(date.getMonth() + 3)
.setDate(date.getDate() - 1)
)
But this returns an error: TypeError: date.setMonth(...).setDate is not a function. I think the chaining of methods is not working, so I'll probably have to setDate in the next statement. Is there a way to do this in a single statement of code?
Is there a way to set date and month on a date object in a single statement?
Yes. The following sets the month to January and the day to the first on one statement:
let d = new Date();
d.setMonth(0, 1);
…if I want to add 3 months to a date, then the new date should be one day before the date after 3 months
No, you can't do that in one statement because adding a month needs to consider the number of days in the month. E.g. adding one month to 31 Jan 2020 results in
31 Feb, and since there were only 29 days in Feb 2020, the date is set to 2 Mar 2020. Similarly, adding 1 month to 31 May gives 31 Jun which rolls over to 1 Jul. So you need to add months first (see Adding months to a Date in JavaScript), then subtract one day (see Add days to JavaScript Date).
You could extend the Date Object and create your own methods which are chainable.
class MyDate extends Date {
constructor() {
super(...arguments)
}
changeMonth(amount) {
return new MyDate(this.setMonth(this.getMonth() + amount));
}
changeDate(amount) {
return new MyDate(this.setDate(this.getDate() + amount));
}
};
const date = new MyDate();
console.log("Original:", date);
console.log("Changed :", date.changeMonth(3).changeDate(-5));
You could so something like
newDate = new Date(newDate.getFullYear(), newDate.getMonth() + 3, endDate.getDate() -1)
Turns out there is a very simple solution. The setMonth() method allows us to pass an optional dayValue parameter (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMonth). Using which, the code simply becomes:
new Date(
date.setMonth(
date.getMonth() + 3,
date.getDate() - 1
)
)

Get day name from date with format dd-mm-yyyy?

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))

How can I add a day to user's input? [duplicate]

This question already has answers here:
How to add days to Date?
(56 answers)
Closed 9 years ago.
I have a textfield that inputs date in this format: yyyy-mm-dd, how can I add a day to that users input? I have the following code but it doesnt work...
users_date = document.getElementById('users_date').value;
var date = new Date(users_date);
var next_date = new Date();
next_date .setDate(date.getDate()+1);
document.getElementById('next_date').value = next_date;
The first problem is the format of the date in the second is like 'Mon Aug 05 2013 16:24:40 GMT-0500 (Hora est. Pacífico, Sudamérica)'
The second problem is that when the user input the fist day of the month like '2013-01-01' or '2013-08-01' it displays 'Sun Sep 01 2013 16:26:06 GMT-0500 (Hora est. Pacífico, Sudamérica)' ALWAYS
For example if user inputs 2013-01-01 I want another textfield to be 2013-01-02 or 2013-08-31 it displays 2013-09-01, how can I do that?
Thanks!!
ITS NOT DUPLICATE BECAUSE THE OTHER POST DOESN'T FORMAT THE DATE!!!!
Prior to ES5 there was no standard for parsing dates. Now there is a format that is a version of ISO8601, however it isn't supported by all browsers in use and is not typically used for user input.
Normally a format is requested or a "date picker" used that returns a specific format. From there, it's quite simple to parse the string to create a Date object:
// s is date string in d/m/y format
function stringToDate(s) {
var b = s.split(/\D/);
return new Date(b[2], --b[1], b[0]);
}
For ISO8601 format (y-m-d), just change the order of the parts:
// s is date string in y/m/d format
function isoStringToDate(s) {
var b = s.split(/\D/);
return new Date(b[0], --b[1], b[2]);
}
To add one day to a Date object, just add one day:
var now = new Date();
var tomorrow = now.setDate(now.getDate() + 1);
This should work:
var date = new Date(document.getElementById('users_date').value);
var next_date = new Date(date.getTime() + 24*60*60*1000); // adding a day
document.getElementById('next_date').value = next_date.getFullYear() + "-" +
(next_date.getMonth()++) + "-" + next_date.getDate();
Please, note that Date#getMonth() is zero-based. Hence, the increment.

Categories