Subtract x days from a String Date - React - javascript

Suppose I've got a date in string format, such as "2021-07-19". How can I subtract x days from this date that is represented as a string?
I have tried to convert the string into a date first, then subtract the number of days, and convert back to a string, but that doesn't work.
const dateString = "2021-07-19"
const previousDayDate = new Date(dateString)
previousDayDate.setDate(previousDayDate.getDate() - 1)
const previousDayDateString = previousDayDate.toString()
The ultimate result should be "2021-07-18". Instead, I get the date as a full string: Sun Jul 18 2021 01:00:00 GMT+0100 (British Summer Time)

The reason you get the wrong date is that "2021-07-19" is parsed by built–in parsers as UTC, but all the other methods you're using are local, so you appear to get the wrong date or time. Other than that, your algorithm is sound. Just parse the string as local to being with:
// Parse string in YYYY-MM-DD format as local
function parseISOLocal(s) {
let [Y, M, D] = s.split(/\W/);
return new Date(Y, M-1, D);
}
console.log(parseISOLocal('2021-07-20').toString());
This is a very common issue.

Note, the snippet below didn't work in my locale until I changed the input date to YYYY-MM-DD.
// const dateString = "2021-19-07" - your format
const dateString = "2021-07-19" // format testable in my locale
const previousDayDate = new Date(dateString)
previousDayDate.setDate(previousDayDate.getDate() - 1)
const previousDayDateString = `${previousDayDate.getFullYear()}-${('0' + (previousDayDate.getMonth()+1)).slice(-2)}-${('0' + previousDayDate.getDate()).slice(-2)}`;
console.log(previousDayDateString)

Using Moment.js
const dateString = moment("2021-07-19", "YYYY-MM-DD").startOf("day")
const previousDayDateString = dateString.subtract(1, "days").format("YYYY-MM-DD");

Thank you all for the suggestions. I followed the same convention as Spencer's comment above (How to format a JavaScript date?) by doing:
const dateString = "2021-07-19"
const previousDayDate = new Date(dateString)
previousDayDate.setDate(previousDayDate.getDate() - 1)
const previousDayString = previousDayDate.toLocaleDateString("en-CA").split(",")[0]
console.log(previousDayString)

Related

How to format a Date in a Specific Format in React.js?

I want to show the full date formatted from this 2020-11-09T17:50:00.000Z
to this 22/1/2020 14:20:22 format. I know how get the desired format via moment.js, but want to achieve this with JavaScript Date.
Here is what I have now, but this is not what I want.
let d = new Date("2020-11-09T17:50:00.000Z".toLocaleString("en-US"))
console.log(d);
Any help will be appreciated
You can always do it manually, the Date API only has a limited set of functions like .toLocaleDateString() which will give you "11/9/2020" and .toGMTString() will return "Mon, 09 Nov 2020 17:50:00 GMT".
Using your Date APIs, you can build the string yourself using what you have.
var timeString = d.toGMTString().split(" ")[4]; //This will return your 17:50:00
//For the date string part of it
var dateNumber = d.getDate();
var monthNumber = d.getMonth() + 1;
var yearNumber = d.getFullYear();
var dateString = `${dateNumber}/${monthNumber}/${yearNumber}`;
var finalDateString = [dateString, timeString].join(" ");
toLocaleString() can produce many formats, and you can choose the locale to get the format (or close to it) that you want.
The locale "en-GB" gives you almost what you want; you just need to remove the comma that it puts in...
let d = new Date(2020, 0, 22, 14, 20, 22);
let output = d.toLocaleString("en-GB")
.replace(',' ,'');
console.log(output);
You can actually control the output further by using the options parameter.
But also see the Intl object for its DateTimeFormat constructor.

Angular : Convert Object into Date and Moment

I am receiving a form value for date in Kendo Datepicker. It comes in as an object.
1)
How do I convert the following to date?
The following in Debugger still left it as Object
new Date(this.editHeaderAddressForm.value.seasonalEnd);
2) Additionally, how can I convert it to Moment?
The Date.parse() method parses a string representation of a date, and returns the number of milliseconds
var javaScriptRelease = Date.parse('04 Dec 1995 00:12:00 GMT');
var newDate = Date('December 17, 1995 03:24:00');
console.log(javaScriptRelease);
> // expected output: 818035920000
console.log(newDate);
> // expected output: Sun Dec 17 1995 03:24:00 GMT...
You can get date, and moment with short and simple code.
var full_time = new Date(this.editHeaderAddressForm.value.seasonalEnd);
var date = full_time.toLocaleDateString();
var moment = full_time.toLocaleTimeString();
console.log(date);
console.log(moment);
Use Date.parse method
const epochValue = Date.parse(this.editHeaderAddressForm.value.seasonalEnd);
This will return date in EPOCH this you can directly pass in to Moment function as well.
moment.unix(epochValue)

UTC date convert to local timezone

I have a date in UTC format.
"2016-10-12 05:03:51"
I made a function to convert UTC date to my local time.
function FormatDate(date)
{
var arr = date.split(/[- :T]/), // from your example var date = "2012-11-14T06:57:36+0000";
date = new Date(arr[0], arr[1]-1, arr[2], arr[3], arr[4], 00);
var newDate = new Date(date.getTime()+date.getTimezoneOffset()*60*1000);
var offset = date.getTimezoneOffset() / 60;
var hours = date.getHours();
newDate.setHours(hours - offset);
return newDate;
}
My Local timezone is GMT +0530.
My code produced this output:
Tue Oct 11 2016 10:33:00 GMT+0530 (IST)
I converted the date with an online tool to get the correct date and time.
Wednesday, October 12, 2016 10:30 AM
My code matches the online tool on time but not on date.
How can I correct my code's output, preferably using moment.js?
UTC is a standard, not a format. I assume you mean your strings use a zero offset, i.e. "2016-10-12 05:03:51" is "2016-10-12 05:03:51+0000"
You are on the right track when parsing the string, but you can use UTC methods to to stop the host from adjusting the values for the system offset when creating the date.
function parseDateUTC(s){
var arr = s.split(/\D/);
return new Date(Date.UTC(arr[0], arr[1]-1, arr[2], arr[3], arr[4], arr[5]));
}
console.log(parseDateUTC('2016-10-12 05:03:51').toLocaleString());
If you want to use moment.js, you can do something like the following. It forces moment to use UTC when parsing the string, then local to write it to output:
var d = moment.utc('2016-10-12 05:03:51','YYYY-MM-DD HH:mm:ss');
console.log(d.local().format());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.0/moment.js"></script>
Since you have tagged moment, I'm assuming you are using moment.
In such cases, you should keep your approach consistent and not mix moment and date object.
var dateStr = '2016-10-12 05:03:51';
var timeZone = "+0530";
var date = moment.utc(dateStr).utcOffset(dateStr + timeZone)
console.log(date.toString())

How To Convert String ' dd/mm/yy hh:MM:ss ' to Date in javascript?

I have Done this
var d='dd/mm/yy hh:MM:ss';
var d1=d.split(" ");
var date=d1[0].split("/");
var time=d1[1].split(":");
var dd=date[0];
var mm=date[1]-1;
var yy=date[2];
var hh=time[0];
var min=time[1];
var ss=time[2];
var fromdt= new Date("20"+yy,mm-1,dd,hh,min,ss);
Is there Any way to do it using JQuery OR JavaScript?
If you are looking for alternatives in jquery or Javascript , then you can go with Moment.js,where you can Parse, Validate, Manipulate, and Display dates in JavaScript.
example:
var date= moment("06/06/2015 11:11:11").format('DD-MMM-YYYY');
This will work regardless of timezone for the format dd/mm/yyy hh:mm:ss only. It also does not rely on third party packages:
let dtStr = "12/03/2010 09:55:35"
console.log(strToDate(dtStr)); // Fri Mar 12 2010 09:55:35
function strToDate(dtStr) {
if (!dtStr) return null
let dateParts = dtStr.split("/");
let timeParts = dateParts[2].split(" ")[1].split(":");
dateParts[2] = dateParts[2].split(" ")[0];
// month is 0-based, that's why we need dataParts[1] - 1
return dateObject = new Date(+dateParts[2], dateParts[1] - 1, +dateParts[0], timeParts[0], timeParts[1], timeParts[2]);
}
How about Date.parse()?
new Date( Date.parse("05/12/05 11:11:11") );
// Thu May 12 2005 11:11:11 GMT+0200 (CEST)
The output produced is in local timezone and will differ in browsers in different timezones.
We can convert any local date format to datetime datatype using moment js.
Syntax:
moment('<local date value>','<local date format>').format('<expected convert format>')
Example:
moment('26/05/1986 00:00', 'DD/MM/YYYY HH:mm').format("MM/DD/YYYY HH:mm");
then the output will be 05/26/1986 00:00
Cheers
Date#parse should be able to parse that if you split on a string. Id also recommend looking into the npm package moment for date manipulation
From your code it seems that you are trying to convert string into date and also you are trying to fetch previous month. If yes then you can reconstruct your code as below:
Date.prototype.SubtractMonth = function(numberOfMonths) {
var d = this;
d.setMonth(d.getMonth() - numberOfMonths);
return d;
}
$(document).ready(function() {
var dateString='2015-06-17T18:30:12';
var d = new Date(dateString);
alert(d.SubtractMonth(1));
});

JS: new Date() is not accepting date string in my own locale (d/m/y)

My browser (ie. my OS) should know I'm in Australia and what the correct date format is. In this case, d/m/y, not m/d/y. However if I run the following code:
alert(new Date("21/11/1968"))
The result is "Thu Sep 11 1969". It is thinking the month comes first and adjusting accordingly.
Why is this? Is the answer to always use a universal format as input to date functions, or is there a way to tell the browser to expect dates input in my locale format?
It's pretty simple to convert your date string to a format that will give the expected result ('yyyy/mm/dd' or 'yyyy-mm-dd'):
new Date("21/11/1968".split('/').reverse().join('/'));
[edit] You may like this more generic method (part of the npm PureHelpers library):
document.querySelector("#result").textContent = `
tryParseDate("2017/03/22", "ymd"); // ${tryParseDate("2017/03/22", "ymd")}
tryParseDate("03/22/2017", "mdy"); // ${tryParseDate("03/22/2017", "mdy")}
tryParseDate("22-03-2017", "dmy"); // ${tryParseDate("22-03-2017", "dmy")}
`;
function tryParseDate(dateStringCandidateValue, format = "dmy") {
if (!dateStringCandidateValue) {
return null;
}
const mapFormat = format.split("").reduce(function(a, b, i) {
a[b] = i;
return a;
}, {});
const dateStr2Array = dateStringCandidateValue.split(/[ :\-\/]/g);
const datePart = dateStr2Array.slice(0, 3);
const datePartFormatted = [
+datePart[mapFormat.y],
+datePart[mapFormat.m] - 1,
+datePart[mapFormat.d]
];
if (dateStr2Array.length > 3) {
dateStr2Array.slice(3).forEach(t => datePartFormatted.push(+t));
}
const dateTrial = new Date(Date.UTC.apply(null, datePartFormatted));
return dateTrial && dateTrial.getFullYear() === datePartFormatted[0] &&
dateTrial.getMonth() === datePartFormatted[1] &&
dateTrial.getDate() === datePartFormatted[2]
? dateTrial
: null;
}
<pre id="result"></pre>
The Date object is very weak. You cannot tell it what format to expect. You can create it with a string in m/d/y like you stated, or new Date(year, month, day[, hours, seconds, milliseconds]);
new Date(string_date) supports the following Date formats:
MM-dd-yyyy
yyyy/MM/dd
MM/dd/yyyy
MMMM dd, yyyy
MMM dd, yyyy
You need to parse it using a new date object like
const myDate = new Date('Wed Dec 30 2020 00:00:00 GMT-0500 (Eastern Standard Time)')
Then convert it:
const dateFormatted = myDate.toLocaleDateString("en-US")

Categories

Resources