Remove 1 week from a date and keep the format - javascript

How can I remove 1 week from a date with JS without altering the date format (YYYY-MM-DD).
I saw several exemple but with the current date.
What I tried:
actual = '2017-04-10';
actual.setDate(actual.getDate() - 7);
Thanks.

You need to convert your string to a Date first.
Then, to get the format YYYY-MM-DD you can use .toISOString() and keep only the first 10 characters:
var d = new Date('2017-04-10'); // convert string to Date
d.setDate(d.getDate() - 7); // remove 7 days
var str = d.toISOString().slice(0, 10); // format YYYY-MM-DD
console.log(str);

Your date needs to be a date object:
actual = new Date('2017-04-10');
actual.setDate(actual.getDate() - 7);

The format is dictated by your operating system's regional settings and the format method you call on your date:
// You first need to turn your string into an actual JavaScript date:
actual = new Date('2017-04-10');
// Then you can use the Date API to modify it:
actual.setDate(actual.getDate() - 7);
// But the formatting of the date is determined by your operating system
// regional settings and the Date formatting method you call as well as
// how you, yourself decide to build your own custom format:
console.log(actual);
console.log(actual.toLocaleTimeString());
console.log(actual.toLocaleDateString());
console.log(actual.toISOString());
console.log(actual.getFullYear() + "-" + (actual.getMonth() + 1) + "-" + actual.getDate());

Related

Jquery new Date - Convert to yyyy-MM-dd and use toLocaleDateString

I have a HTML input box set to type=date
<input name="datereceived" type="date" class="FormDateValues" id="datereceived" />
I want to use Jquery to fill this input box on document load to today's date but because I am in Australia, I have to offset using GMT+10
To get the date, I do the following:
var newDate = new Date();
and then I tried to set the input box using the following:
$('#datereceived').val(newDate.toLocaleDateString());
The browser tells me that for type=date, the format must be set to yyyy-MM-dd and not the Australian time format of dd/MM/yyyy.
I am not sure how to go about enforcing the toLocaleDateString AND converting the date to yyyy-MM-dd.
Try using fr-CA that returns the format in yyyy-MM-dd.
var yyyymmdd = (new Date ()).toLocaleDateString ("fr-CA");
console.log (yyyymmdd);
If you need the local date (GMT+10 in your case), you need to use methods of Date:
function toHtmlDate (d) {
return (d.getFullYear() + '-0' + (d.getMonth() + 1) + '-0' + d.getDate()).replace(/-0(\d\d)/g, '-$1');
}
If you need an ISO date (GMT), you can use new Date().toISOString().substring(0, 10). For explanation:
Date.prototype.toLocaleDateString output depends on your locale, using string splitting on it might not work for another user
Date.prototype.toISOString always returns ####-##-##T##:##:##.###<timezone>, for example 2015-10-18T23:23:22.880Z. Take the first 10 characters, you have <year>-<month>-<date>.
Try using String.prototype.split() , Array.prototype.splice() , Array.prototype.join()
// create array of values returned by `.toLocaleDateString()`,
// delimited by `/`
var d = new Date().toLocaleDateString().split("/");
// `y` : year
var y = d.splice(-1)[0];
// set `y` as item at index `0` of `d`
d.splice(0, 0, y);
// join items within `d` with dash character `"-"`
var date = d.join("-");
console.log(date);
Apart from solution mentined:
If you have jQuery UI loaded:
// jQuery UI datepicker
$.datepicker.formatDate("yy-mm-dd", new Date())
If you have Moment.JS
// Moment JS
moment().format("YYYY-MM-DD")
If you need additional tools for parsing, formatting, comaping dates or converting them between time zones, I recommend to have a look at Moment.js library.
With toISOString and slice:
var today = new Date().toISOString().slice(0, 10)
console.log(today)

How do I format a date as ISO 8601 in moment.js?

This docs mention moment.ISO_8601 as a formatting option (from 2.7.0 - http://momentjs.com/docs/#/parsing/special-formats/), but neither of these work (even 2.7.0):
var date = moment();
date.format(moment.ISO_8601); // error
moment.format(date, moment.ISO_8601); // error
(http://jsfiddle.net/b3d6uy05/1/)
How can I get an ISO 8601 from moment.js?
moment().toISOString(); // or format() - see below
http://momentjs.com/docs/#/displaying/as-iso-string/
Update
Based on the answer: by #sennet and the comment by #dvlsg (see Fiddle) it should be noted that there is a difference between format and toISOString. Both are correct but the underlying process differs. toISOString converts to a Date object, sets to UTC then uses the native Date prototype function to output ISO8601 in UTC with milliseconds (YYYY-MM-DD[T]HH:mm:ss.SSS[Z]). On the other hand, format uses the default format (YYYY-MM-DDTHH:mm:ssZ) without milliseconds and maintains the timezone offset.
I've opened an issue as I think it can lead to unexpected results.
Use format with no parameters:
var date = moment();
date.format(); // "2014-09-08T08:02:17-05:00"
(http://jsfiddle.net/8gvhL1dz/)
Also possible with vanilla JS
new Date().toISOString() // "2017-08-26T16:31:02.349Z"
When you use Mongoose to store dates into MongoDB you need to use toISOString() because all dates are stored as ISOdates with miliseconds.
moment.format()
2018-04-17T20:00:00Z
moment.toISOString() -> USE THIS TO STORE IN MONGOOSE
2018-04-17T20:00:00.000Z
var date = moment(new Date(), moment.ISO_8601);
console.log(date);
If you just want the date portion (e.g. 2017-06-27), and you want it to work regardless of time zone and also in Arabic, here is code I wrote:
function isoDate(date) {
if (!date) {
return null
}
date = moment(date).toDate()
// don't call toISOString because it takes the time zone into
// account which we don't want. Also don't call .format() because it
// returns Arabic instead of English
var month = 1 + date.getMonth()
if (month < 10) {
month = '0' + month
}
var day = date.getDate()
if (day < 10) {
day = '0' + day
}
return date.getFullYear() + '-' + month + '-' + day
}
Answer in 2020 (Includes Timezone Support)
The problem we were having is that, by default, ISOStrings aren't localized to your timezone. So, this is kinda hacky, but here's how we ended up solving this issue:
/** Imports Moment for time utilities. */
const moment = require("moment-timezone")
moment().tz("America/Chicago").format()
//** Returns now in ISO format in Central Time */
export function getNowISO() {
return `${moment().toISOString(true).substring(0, 23)}Z`
}
This will leave you with an exact ISO-formatted, localized string.
Important note: Moment now suggests using other packages for new projects.
If you need the formatting string : YYYY-MM-DDTHH:mm:ssZ
var date = moment();
console.log(date.format("YYYY-MM-DDTHH:mm:ssZ"));
var x = moment();
//date.format(moment.ISO_8601); // error
moment("2010-01-01T05:06:07", ["YYYY", moment.ISO_8601]);; // error
document.write(x);

Convert date from json to regular format in jquery mobile

I got from json with date, date format is "2011-03-13T11:30:00Z" , and I want to convert it into normal format .
var Date= "Sunday, March 13th, 2011 " and var Time = "11:30"
i want to make it separate as above with proper format.
please help me....
Create a new Date object with the date string from the json data and then use the objects methods to get the date formats you want
var dateObject = new Date("2011-03-13T11:30:00Z");
var time = dateObject.getHours() + ':' + dateObject.getMinutes();
You also have the following which you could use to construct your date
dateObject.getDay(); // would return 0 for Sunday (days run 0-6 starting at Sun)
dateObject.getMonth(); // would return 2 for March (months run 0-11)
dateObject.getFullYear(); // return 2011
As per comments, to correct this for timezones, you need to know that the Z in your string denotes UTC/GMT, so if you are not in that timezone you need to correct for your difference to UTC
For example, replace the Z with +05:30 for being 5.5 hours ahead of UTC
var dateString = "2011-03-13T11:30:00Z".replace('Z', '+05:30');
var dateObject = new Date(dateString);

how to compare date which is given by user to date in javascript..?

In my web-site I am getting a date from user which in format like "dd-mm-yyyy",now I want to get the date which is 7-day before of that user's date.
I am able to get the current date in format "dd-mm-yyyy" but how would I know the date which is one week before user's date in javascript?
If you already have a Date object, use yourDate.setDate(yourDate.getDate() - 7 );
Try this--
var MyDate = new Date('11/30/2012'); //date format in mm/dd/yyyy
MyDate.setDate(MyDate.getDate() -7)
var newDate = MyDate.getMonth()+1 + '/' + MyDate.getDate() + '/' + MyDate.getFullYear()
alert(newDate);
Note- subtracting seven days to a date shifts the month or year and the changes are handled automatically by the Date object.
Why don't you use datejs, it's the best date related js library I have seen. Chcek the documentation here.
http://code.google.com/p/datejs/wiki/APIDocumentation
Search for add method
Set Dates
We can easily manipulate the date by using the methods available for the Date object.
In the example below we set a Date object to a specific date (14th January 2010):
var myDate=new Date();
myDate.setFullYear(2010,0,14);
And in the following example we set a Date object to be 7 days in past:
var myDate=new Date(); //or users date
// myDate will be users current date
myDate.setDate(myDate.getDate()-7);
//now substract 7 days to get the date u want.
Follow the following link
http://www.w3schools.com/js/js_obj_date.asp
Or follow this
http://www.techrepublic.com/article/manipulate-time-and-date-values-with-javascripts-date-object/6076869
You can convert a date string in the format dd-mm-yyyy to a date object using:
function toDate(d) {
d = d.split('-');
return new Date(d[2], --d[1], d[0]);
}
Then use Osiris' answer to add or subtract 7 days.

How to format JSON date?

so, i need format JSON date from this format
"9/30/2010 12:00:00 AM", it is MM/DD/YYYY HH:MM:SS to format like this : DD/MM/YYYY, so i dont need info about hours, min and sec, and i need replace months and days from json, i tried some different ways but it always failed
i need do this using jQuery
also i didnt find any answer to formating this date type, all i found was formating date like this :/Date(1224043200000)/
so anyone have idea?
you can create a Date Object from a string like so:
var myDate = new Date(dateString);
then you can manipulate it anyway you want, one way to get your desired output is:
var output = myDate.getDate() + "\\" + (myDate.getMonth()+1) + "\\" + myDate.getFullYear();
you can find more at this elated.com article "working with dates"
Unfortunately your "from" dateformat is not the one which is implementation-independent in JavaScript. And all the other formats depends on the implementation, which means even if this format would be understood by most of the implementation I/you can't be sure for example how the DD and MM order would be parsed (I am almost sure it would be local regional settings dependent). So I would recommend to use a 3rd party (or your hand written) date parser to get a Date object out of your input string. One such parser you can find here:
http://www.mattkruse.com/javascript/date/
Because your question is not 100% clear for me, it's possible that you have your date in the format of /Date(number)/ which suggests that you are calling an ASP.Net service from your jQuery code. In this case during the JSON parse you can convert it to a Date object:
data = JSON.parse(data, function (key, value) {
// parsing MS serialized DateTime strings
if (key == '[NAME_OF_DATE_PROPERTY_IN_THE_JSON_STRING]') {
return new Date(parseInt(value.replace("/Date(", "").replace(")/", ""), 10));
// maybe new Date(parseInt(value.substr(6))) also works and it's simpler
}
return value;
});
The code below solved my problem:
var date = new Date(parseInt(d.data[i].dtOrderDate.replace("/Date(", "").replace(")/", ""), 10));
var day = date.getDate();
var monthIndex = date.getMonth();
var year = date.getFullYear();
Try something like this :
var date = new Date(parseInt(jsonDate.substr(6)));
where jsonDate is variable that stores your date

Categories