This question already has answers here:
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 5 years ago.
How do I format a date using javascript: for example, change "2018-10-25T15:00:00.000Z" to Sat, "10/25" ?
Please and thank you
Using toLocaleString you could do:
console.log(
(new Date())
.toLocaleString(
window.navigator.language,
{month:"2-digit",day:"2-digit",weekday: 'short'}
)
);
console.log(
(new Date())
.toLocaleString(
"zh-CN",
{month:"2-digit",day:"2-digit",weekday: 'short'}
)
)
Using toLacaleString will get you a string based on locale and as Rob pointed out in the comment; this may differ even in different browsers.
If you want to show the user a local string then this is good but if you want to automatically process that string it's better to use something else like milliseconds after epoch UTC.
The format you provided would suggest user only because it's unfit for automatic processing (there is no timezone or year).
Maybe you are trying to combine formatted string to show the user with something you need to process later. In that case I would advice you to use tuple (array) that contains both ms after epoch and user formatted string.
Anyway, if you want to mix up formatted for human consumption with automation then you can do the following:
var d = new Date();
["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][d.getDay()]+", "+
new String("0"+(d.getMonth()+1)).slice(-2) + "/" +
new String("0"+d.getDate()).slice(-2)
Moment.js library could probably save you a lot of time with this tedious task:
moment(new Date('2018-10-25T15:00:00.000Z')).format("dddd, MM/D")
output:
"Thursday, 10/25"
You can mess around with it by opening the JS console on their docs page, as moment is loaded on it.
Edit- as noted in comments, if this is the only task you are using it for, probably best not to use a lib and do it in plain JS!
Related
This question already has answers here:
Converting Unix timestamp to Date Time String [duplicate]
(2 answers)
How do I format a date in JavaScript?
(68 answers)
Closed 3 years ago.
I want to know how to convert a long date like this 1542814586896 into a String format like this 2019/02/05
You can use Date class for setting time in integer format and getting any values like day, month, year
let date = new Date(1542814586896);
console.log(date.getDay(), date.getMonth(), date.getFullYear())
You can use
new Date(1542814586896).toLocaleDateString(`ja-JP`);
//-> "2018/11/21"
.toLocaleDateString() formats time into a format of a specific region. In the example above, time's formatted into Japanese format (just because it seems like in Japan they use exactly the format you need).
What's cool about this method is that you may just pass no argument to toLocaleDateString & it will then just automatically pick the format that the final user prefers (or more precisely, the format that is set in user's OS).
For example in my browser:
new Date(1542814586896).toLocaleDateString();
//-> "21/11/2018"
However, if I had Egyptian Arabic set as main language of my operating system, the result should be like:
new Date(1542814586896).toLocaleDateString();
//-> "٢١/١١/٢٠١٨"
You may find more information about different locales & corresponding formats here.
Similar questions has been asked many times but I couldn't find a more concrete solution. The things I'm doing are:
I have a <input type="date"> inside my HTML which when clicked opens a calender with date in dd/mm/yyyy format.
I change the html5 date to timestamp to send to my db by Date.parse(html5Date) and in the server I modify the date and send it back to my Angular app.
I now convert the timestamp back to Date object by new Date(timestamp).To print the date in a human-friendly format inside a table I do [date.getDate(), date.getMonth() + 1, date.getFullYear()].join('/').
On edit (PUT request), I again capture the date from HTML, convert it to timestamp, send it to server and process the returning date back to html date.
Other than these, I also do a ton of functionalities like date comparison, adding hours to the dates, show time of the day etc inside the HTML:
Just these simple operations are over 120 lines of code which I think is ridiculous and error prone. I've looked into Angular Datepicker but it's a bit confusing. Also sometimes the HTML date is of type Object and sometimes it's String so Date.parse() gives error.
Are there any developer friendly methods that does : copy HTML5 date (from datepicker) --> change to timestamp (for angular&server) --> format timestamp back to string/object (for html)? Thank You :)
Note: Angular throws a lot of annoying error in console saying dateformat is wrong (being html date type) but doesn't stop code from running
Sounds like you are doing waaay to many conversions. I would argue that there should only be one way dates are represented: as Date objects in the programming language. There are only a few conversions that need to happen:
Date <=> Integer milliseconds since the epoch to pass to server
Date <=> String human-readable format to display to user
Any thing beyond this is asking for trouble. Comparisons can be made by casting to int date.getTime(), comparing, and casting back to Date. Ditto for additions. Note that Date.parse is implementation dependent in what it will accept, although all of them will accept ISO 8601 formatted date strings anything else is guesswork. Which means you will have to deal with converting strings by hand, something like the following:
var toDate = str => {
var splitter = str.indexOf("/") === -1 ? "-" : "/";
var [mon, day, year] = str.split(splitter);
return new Date(year, mon - 1, day);
};
var toDateString = date => {
return "" + date.getFullYear() + (date.getMonth() + 1) +...
};
Note that there's no validation, that's left as an exercise to the reader.
A WORD ABOUT MOMENT.JS
moment.js is awesome. Its also huge, its a kitchen-sink API with a heft to match. You're already loading angular, so think carefully before bulking the size of your payload with another huge library.
Moment.js is a powerful date formatting and manipulation library. A lot of things you can do in Moment.js are a single line of code, which makes life a lot easier. I agree, without using a library like this date formatting and handling can be a pain.
http://momentjs.com/
EDIT: fyi, I use this with my Angular app and find it extremely useful!
I get from my client a date in this format:
2012-11-07T00:00:00 (yyyy-mm-ddT00:00:00)
How can I parse it into a Date object?
My first option is:
getting the first 10 characters (2012-11-07)
split that by "-"
creating new Date(splitted[0],splitted[1],splitter[2])
I know that such a question is obvious and over-answered, not only in Stack Overflow, but I want to:
know a better practice WITHOUT any library, pure JS ( Date.parse() ? )
the same with a widely used date library / framework for nodeJS
var d = new Date('2012-11-07T00:00:00')
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Help parsing ISO 8601 date in Javascript
I think this should be very simple but turned out amazingly tedious.
From WEB API, I received selected object via ajax, and one of its properties is InspectionDate datetime string such as 2012-05-14T00:00:00
In javascript, I use following code to have correct date object
selected.JsInspectionDate = new Date(selected.InspectionDate);
But JsInspectionDate shows
2012/05/14 00:00 in firefox,
2012/05/13 20:00 in chrome and
NAN in IE9
for 2012-05-14T00:00:00.
Could someone tell me why this problem occurs? And how to fix this issue? I just want to show as in firefox for all browsers.
Do this:
new Date(selected.InspectionDate + "Z")
Rationale: Your dates are in ISO 8601 form. Timezone designators like "Z", a very short one for UTC, work.
Note! IE might not understand ISO 8601 dates. All bets are off. In this case, better use datejs.
Update:
First as one suggested, I tried following after referencing date.js.
selected.JsInspectionDate = Date.parse(selected.InspectionDate);
It seemed like working but later I found it was not enough since the JSON date string can have a format of 2012-05-14T00:00:00.0539 which date.js can't process either.
So my solution was
function dateParse(str) {
var arr = str.split('.');
return Date.parse(arr[0]);
}
...
selected.JsInspectionDate = dateParse(selected.InspectionDate);
FIDDLE
var selectedDate='2012-05-14T00:00:00';
var formatttedDate=new Date(selectedDate.substr(0,selectedDate.indexOf('T')));
document.write(formatttedDate.getFullYear()+'/'+(formatttedDate.getMonth()<10?'0'+formatttedDate.getMonth():formatttedDate.getMonth())+'/'+formatttedDate.getDay());
I am currently having some issues converting a string dateTime object in JavaScript
I am assuming it is because my string cannot me used properly in a new Date() but I'm not sure that is the problem.
My Input: "2011-09-29 14:58:12"
My code:
var date = "2011-09-29 14:58:12";
var added = new Date(date);
var year = added.getYear();
However, my year var contains NaN. Same with getDay() or getMonth(). What is the problem?
ps: I'm getting the date in it's format from a SQLite database. And I'm using Titanium Mobile, so javascript and SQLite are the only things involved
You're relying on the Date constructor parsing an unsupported format. Until recently, there was no standard string format supported by the Date constructor. As of ECMAScript5, there is one (YYYY-MM-DDTHH:MM:SS, note the T rather than space), but it's only been specified for just under two years and naturally doesn't work in older browsers.
For the time being, your best bet is to parse it yourself (you can find code in this question and its answers), or use something like DateJS, MomentJS, date-fns, etc. to parse it for you.
The Date constructor will not parse a string for you. You'll need to use Date.parse to do that. Interestingly enough, Date.parse doesn't actually return a Date. Instead it returns a unix timestamp. You can then pass the unix timestamp into the Date constructor to get what you're looking for.
var d = new Date(Date.parse("2011-09-29 14:58:12"));