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

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)

Related

Remove 1 week from a date and keep the format

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

How to do a date format in Javascript?

I need to understand how to do date formattting in javascript.
i have date as,
var date="12/02/1994";// dd/mm/yyy
var date1=new Date(date);
date1.getDate();// this gives me Month which is 02
date1.getMonth();// this gives me date which is 12.
How do i get the exact date i have in var date in get date and getmonth function? Please help
The answer is pretty simple: JavaScript uses mm/dd/yyyy data format.
It doesn't support dd/mm/yyyy format, so, if you need to parse this format, then you will have to do this manually like this:
function parseDdmmyyyy(str)
{
var spl = str.split('/');
return new Date(spl[2], spl[1] - 1, spl[0]);
}
or you will have to use external libraries like Moment.js.
Javascript date() expects date in mm/dd/yy and not in dd/mm/yy. And months start from 0 and not 1.
var from = "12/02/1994".split("/");
var date1 = new Date(from[2], from[1] - 1, from[0]);
date1.getDate();
date1.getMonth();
Use new Date('02/12/1994'), new Date('1994-02-12') or new Date(1994, 02-1, 12), because in js months start from 0 and american date format is used where month goes first
you can use the simple JS file DateFormat.js which has some very good example through the URL mattkruse (Date Funtion)
from this JS file you can validate the incoming date is a true format even you can add format date within a several ways.
Presumably you want to know how to format strings so they are consistently parsed by browsers. The short answer, is there is no guarantee that any particular string will be correctly parsed by all browsers in use (or perhaps even most).
So the bottom line is: don't parse strings with the Date constructor, ever. It's largely implementation dependent and even the one format specified in ES5 and ECMAScript 2015 is poorly and inconsistently supported.
How browsers treat a string like "12/02/1994" is entirely implementation dependent, however most will treat it as the peculiar US month/day/year format, i.e. 2 December and getMonth will return 11, since months are zero indexed.
So you should always manually parse strings (a library can help, but a simple parsing function is only 2 lines, 3 if validation is required), e.g.
// Parse a date string as d/m/y
// If s is not a valid date, return a Date object with its
// time value set to NaN.
function parseDMY(s) {
var b = s.split(/\D/);
var d = new Date(b[2], --b[1], b[0]);
return d && b[1] == d.getMonth()? d : new Date(NaN);
}
document.write(parseDMY('12/02/1994'));

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

Compare different time zone date in Jquery

How to compare dates from different time zone?
for e.g.
x = "2013-12-02T10:10:17-0400" // (timezone EST)
and compare this date to current date
var d = new Date(); // timezone(PST)
check x < d ?
When it comes to dealing with dates and times in JavaScript, I usually use Moment.js which is a library exactly for this purpose.
Its URL is http://momentjs.com/
Then you can simply parse the given string with this line:
// Parse the given datetime
var mydate = moment("2013-12-02T10:10:17-0400");
And you can also compare two different moment values:
// Compare given datetime with the current datetime
if (moment("2013-12-02T10:10:17-0400") > moment()) {
// ...
}
Or you can just convert it to a regular JavaScript Date object:
// Parse given datetime and convert to Date object
var mydate = moment("2013-12-02T10:10:17-0400").toDate();
// Compare to current datetime
if (mydate > (new Date())) {
// ...
}
Note that the unary + operator also works with moment objects just as you would expect. So +moment() outputs the same as +(new Date()).
It's also very well documented, the Moment.js docs page has a ton of examples and useful info about it.
Better convert any of the dates to a common timezone(better to have UTC)
Now convert the datetime to milliseconds
Compare the milliseconds
Hope you understand
Use this javascript library to manipulate dates in different time zones: https://github.com/mde/timezone-js
It uses the TZ database: http://en.wikipedia.org/wiki/Tz_database

How to create object of Date("23.03.2010")

I have astring directly coming form the database and I am creating object of Date as
Date dt=Date("23.03.2010") and it is comin NaN
whereas when I use Date dt= Date("03/23/2010") it works fine.
Any Idea how I can get this working?.
You can parse the string from the database and then create the date object. You will have to subtract 1 from the parsed month value to get a correct date.
var dateString = "23.03.2010";
var dateParts = dateString.split(".");
var dt = new Date(dateParts[2], dateParts[1] - 1, dateParts[0]);
You must pass string (parsed) dates in MDY format. This is to prevent ambiguity (does 5/6/2010 mean 6th May or 5th June?)
If you prefer, you can use new Date(year, month, day) format, and pass the arguments separately.
The safest way if is you can return the date as milliseconds since 1970-01-01, then you can easily create a Date object from it. Example:
var n = 1269302400000;
var dt = new Date(n);
Note that you'll want to invoke Date with the new operator - from the Mozilla Developer Center:
Invoking Date in a non-constructor
context (i.e., without the new
operator) will return a string
representing the current time.
The same page details the syntax of the Date constructor.
If you are constructing a Date from a string the format accepted is governed by the rules of the Date.parse method. See Microsoft's Date.parse documentation for a summary of these rules.
Give this a try...
var dateParts = '23.03.2010'.split('.');
// -1 from month because javascript months are 0-based
var dateObj = new Date(dateParts[2], dateParts[1]-1, dateParts[0]);
try
d="23.03.2010".split(".");
Date dt=Date([d[1],d[0],d[2]].join("/"))
i think it isn't the most beautiful way.

Categories