How to format JSON dates with JavaScript? - javascript

I have an HTML <input type="date" name="departing" /> which returns for example the date in the following format: 2021-11-07
When I forward this variable to my handlebars, it is being displayed as follows:
Mon Nov 08 2021 01:00:00 GMT+0100 (Central European Standard Time)
I would like to have it displayed as:
07/11/2021
I tried formatting it with date-fns like this:
departing = format(parseISO(departing.getDate()), "dd/MM/yyyy");
But then my handlebar shows: "Invalid Date"
I am so confused. Any ideas on how to get that date to be displayed in the 07/11/2021
format?

First of all create a date object
const newDate = new Date();
Now you can manipulate code to get answer whatever you want
var outputDate = newDate .getDate() + "/" + (newDate.getMonth()+1) + "/" +
newDate.getFullYear();
Output will be looks like 01/11/2021

Well you could go as simple as using #getDate(), #getMonth() and #getFullYear() methods separately then displaying them in the order you'd like like so:
const date = new Date(departing);
const day = date.getDate();
const month = date.getMonth() + 1;
const year = date.getFullYear();
console.log(`${day}/${month}/${year}`);
Hope it answers the question.

You could do it by several ways
method 1:-
let n = new Date()
console.log(n.toLocaleDateString("en-US")
output=== 31/9/2021
method 2 :- get separate values and merge
let n = new Date()
console.log(n.getDate()+"/"+n.getMonth()+"/"+n.getFullYear())
output=== 31/9/2021

Related

getMonth() in Javascript from format dd/mm/yyyy [duplicate]

This question already has answers here:
Convert dd-mm-yyyy string to date
(15 answers)
Closed 3 years ago.
I have a date in format dd/mm/yyyy and when I try to use getMonth() I get the dd field.
For example if I have "01/12/2019" it will take 01 as month instead of 12. Is there a way to get the month from this format?
This is my code:
var beginDate = document.getElementById("beginDate").value;
var month = new Date(beginDate).getMonth();
inside beginDate there's "01/10/2019" (October 1st 2019)
It's better to use any external libraries like momentjs or datejs. Try this it may solve your problem now.
const date = "01/12/2019";
const split = date.split('/');
console.log('day', split[0])
console.log('month', split[1])
console.log('year', split[2])
var date = moment('01/12/2019', 'DD/MM/YYYY');
console.log(date.month()+1);
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>
You can use something like Moment.js
const beginDate = "22/05/2019"
const date = moment(beginDate, 'DD/MM/YYYY');
const month = date.format('M');
console.log(month)
//05
Make it easy.
You don't need external libraries:
var beginDate = "01/10/2019";
var timeZone = 'your time zone'; //en-GB etc...
var month = new Date(beginDate).toLocaleString(timeZone , {month: "2-digit"}); //month = 10
I don't think that you need some external library to do this task. You should use javascript date object to get it done easily, getMonth() returns month indexed from 0 to 11. Prefer javascript always instead of unnecessarily importing external js files for libraries
var beginDate = document.getElementById("beginDate").value;
let reg = /(\d\d)\/(\d\d)\/(\d+)/gi;
const[date,mon,year] = reg.exec(beginDate).splice(1);
month = new Date(year,mon-1,date).getMonth(); // months are indexed from 0 to 11 for jan to dec
console.log(month); // 0 for jan and 11 for dec
Month in javascript is 0 indexed that mean 0 represent January, So you need to add 1 to get the month correctly
function getMonth(dt) {
let splitDt = dt.split('/');
return new Date(`${splitDt[2]}-${splitDt[1]}-${splitDt[0]}`).getMonth() + 1;
}
console.log(getMonth("01/10/2019"))
1st oct
You can get months using getMonth() as shown below, But here 0=January, 1=February etc.
var date = "05/12/2019"
var d = new Date(date);
var n = d.getMonth();
console.log(n)

Easiest way to create a javascript date from "18th apr 2011" / "1st jun 1980" format

This works:
var myDateString = '19th sep 2015';
myDateString = myDateString.replace('st','');
myDateString = myDateString.replace('th','');
myDateString = myDateString.replace('nd','');
myDateString = myDateString.replace('rd','');
var date = new Date(myDateString);
But is there a cleaner way? Can I pass the date format (including the ordinal part) to the Date constuctor?
I wouldn't rely on it parsing correctly for all people - for instance, people in France might have their locale set to French (surprise) and that would fail to parse apr for instance, because for them it's avr.
Instead, parse it yourself:
var myDateString = '19th sep 2015';
var parts = myDateString.split(" ");
var date = parts[0].replace(/\D/g,''); // keep only numbers
var month = "janfebmaraprmayjunjulaugsepoctnovdec".indexOf(parts[1].toLowerCase())/3;
var year = parts[2];
var date = new Date(year, month, date);
// note because of how we got the month, it's already conveniently zero-based
Use Moment.js library and use your date string like this:
moment('19th sep 2015', 'Do MMMM YYYY').format("D MMMM YYYY")
Output:
"19 September 2015"
The easiest way is to use a library like moment.js or the date part of sugar.js.
To do this properly by hand is not fun.
Update
If you're in full control of the dates, just use ISO 8601 date format, which the constructor of Date understands in any browser.

how to format javascript date dd/mm/yyyy to mm/dd/yyyy

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

Get the last week date in Javascript

Here is my issue:
I have 2 RadDatePickers see below:
<telerik:RadDatePicker ID="rdpTimeOfDayFrom" runat="server" Culture="English (United States)">
<DateInput runat="server" DateFormat="MM/dd/yyyy"></DateInput>
</telerik:RadDatePicker>
<telerik:RadDatePicker ID="rdpTimeOfDayTo" runat="server" Culture="English (United States)">
<DateInput runat="server" DateFormat="MM/dd/yyyy"></DateInput>
</telerik:RadDatePicker>
By using JavaScript I want to get the last week date and set it in the rdpTimeOfDayFrom control the issue is the format is:
Mon Mar 09 2015 17:36:58 GMT-0700 (Pacific Daylight Time)
How can I can I set the return date in that format("yyyy/MM/dd") using Javascript? the reason I'm asking is because after I'm doing post back and trying to get what inisde the control it's been display like that:
3/9/2015 12:00:00AM and I need only the date.
Here is my JS Function:
Using MomentJS
function SetLastWeekDate(sender, args) {
var lastWeekDate = $find("<%=btnTimeOfDayLastWeek.ClientID %>");
var fromDate = $find("<%=rdpTimeOfDayFrom.ClientID %>");
var toDate = $find("<%=rdpTimeOfDayTo.ClientID %>");
var today = new Date();
if (lastWeekDate.get_checked()) {
fromDate.clear();
toDate.clear();
//var lastWeekPeriod = new Date(today.getFullYear(), today.getMonth(),today.getDate() - 7);
var lastWeekPeriod = moment().subtract(7, 'd').format('l');
fromDate.set_selectedDate(lastWeekPeriod);
toDate.set_selectedDate(today);
}
}
this is easy to do with MomentJs
function SetLastWeekDate(sender, args) {
var lastWeekDate = $find("<%=btnTimeOfDayLastWeek.ClientID %>");
var fromDate = $find("<%=rdpTimeOfDayFrom.ClientID %>");
var toDate = $find("<%=rdpTimeOfDayTo.ClientID %>");
var today = moment();
if (lastWeekDate.get_checked()) {
fromDate.clear();
toDate.clear();
var lastWeekPeriod = moment().subtract(7, 'd').format("YYYY/MM/dd");
fromDate.set_selectedDate(lastWeekPeriod);
toDate.set_selectedDate(today);
}
}
if you can set the local of moment to a locale that uses YYYY/MM/DD as the default date display you can simply call format('L'). L is a shortcut in Moment to the locale's default date display.
If I understand well, you need to substract 7 days to the current date.
How about :
Solution 1, with vanilla Javascript :
var d = new Date(); // <- Get the current date
d.setDate(d.getDate() - 7); // <- Substract 7 days
Then format it (this part is a bit weird without library) :
var year = d.getFullYear(),
month = ('00' + (d.getMonth() + 1)).slice(-2),
day = ('00' + d.getDate()).slice(-2);
var formattedDate = year + '/' + month + '/' + day;
Explanation :
d.getMonth() is zero-based so we have to add one
('00' + *number*).slice(-2) is for formatting the number on two digits.
Solution 2 :
If you often need to do some computation or formatting with dates, consider working with a library like momentjs or Date.js. That will really simplify the task. For example, substracting seven days and formatting the date to YYYY/MM/DD with momentjs looks like that :
moment().subtract(7, 'days').format('YYYY/MM/DD');

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