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!
Related
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!
My service is returning this as date 7/14/2016 2:40 AM +00:00. How can I convert this to UTC in JS?
Tried:
new Date("7/14/2016 2:40 AM +00:00").toISOString();
In database the date has been stored as UTC so when I will display the date I want to display as Local time.
There are many ways to parse a string to produce a Date object.
One way is with the Date object itself, either by passing a string to the constructor, or by using Date.parse. However, only the ISO8601 formats are required in the ECMAScript specification. Any other input is implementation specific, and may or may not be recognized by the different JavaScript runtimes. With web browsers in particular, there are many differences in supported formats across browsers.
Additionally, the locale of the environment plays a factor in how the values are parsed. How should 1/2/2016 be parsed? January 2nd, or February 1st? You showed an example of 7/14/2016, which would be invalid input if ran in the UK (for example), where the date format is DD/MM/YYYY.
You can write custom code to split the string up into its parts, parse each part individually, and compose a result. The main problem with this approach is that the code tends to be rigid, and sometimes fragile. It should be well tested, and many edge cases need to be considered.
You can use a library, which is by far the easiest and most flexible approach (IMHO). With a good library, you can take comfort in the shared experiences of others, and in the unit tests that are (hopefully) part of the library you choose. Of course, using a library comes with several tradeoffs including increased file size, and relinquishing some degree of control. You should evaluate these tradeoffs carefully.
There are many date libraries available for JavaScript. The most popular is probably moment.js, though there are others to choose from, and some larger frameworks sometimes have similar functionality already included.
Here is an example using moment.js:
var i = "7/14/2016 2:40 AM +00:00";
var f = "M/D/YYYY h:mm A Z";
var m = moment(i, f);
var o = m.format(f); // will be in the local time, in the same format as the input
var d = m.toDate(); // if you really want a Date object
Assuming you can guarantee that format for all dates, the following code will suffice:
const datetime = '7/14/2016 2:40 PM +00:00'; // this is what your service returns
const pieces = datetime.split(/[/: ]/);
if (pieces[3] == 12) pieces[3] = 0; // fixes edge case for 12 AM/PM
const hours = pieces[5] === 'PM' ? Number(pieces[3]) + 12 : pieces[3];
const d = new Date(Date.UTC(pieces[2], pieces[0] - 1, pieces[1], hours, pieces[4]));
console.log(datetime); // prints "7/14/2016 2:40 PM +00:00"
console.log(d); // prints Date 2016-07-14T14:40:00.000Z
EDIT: There's a couple edge cases with this not handled correctly, namely 12 AM/PM, etc. but those can easily be worked around as well.
EDIT2: Accounted for that edge case.
EDIT3: As a comment stated, this will only work for UTC times. If the string you're receiving can have any offset, this will not work.
var str = "7\/15\/2016 1:00 AM +00:00".replace("+00:00","UTC");
console.log(new Date(str).toISOString()); // 2016-07-15T01:00:00.000Z
Given a datestring, how can I get the format string describing that datestring?
Put another way, how can I get the format string that Date() or MomentJS (might be different for each, that's fine) would use to parse that datestring if one didn't pass an explicit format to use?
So given '2016-01-01' it should output something like 'YYYY-MM-DD', for example.
(I am aware this is a simple question and may have an answer somewhere, but it is difficult to word concisely, so I could only find questions and answers about how to parse datestrings or how to display dates. None about how to output the format itself.)
Consolidating information from Matt Johnson's answer, some comments, and my own contribution.
With Moment.js (version 2.10.7+), you can use the Creation Data API. Something like this in Node.js:
moment('2016-01-01 00:00:00').creationData().format
outputs
'YYYY-MM-DD HH:mm:ss'
Just as any date parsing is, there is ambiguity about the format of many datestrings due to things such as locale (the order of months and days are switched between the US and Europe, for example). But the above method is sufficient for me.
You can't, without having additional information, such as the locale. For example, 01/12/16 could be Jan 12, 2016, December 1, 2016, or December 16, 2001.
Even when you know the locale, there are several places in the real world where more than one date format is used, depending on context.
See https://en.wikipedia.org/wiki/Date_format_by_country
However, if you are just trying to determine which one of multiple known formats was used to parse the input string, moment has an API for that called Creation Data. For example:
var m = moment("2016/06/10", ["YYYY-MM-DD", "MM/DD/YYYY"], true);
var f = m.creationData().format; // "MM/DD/YYYY"
I use the below code to format date time in iso format using java (I'm reducing 1 min from current time) and get the output as this "2016-03-17T11:38:21.xxxZ" < x represent some numbers> i want this to compare with the time which have mentioned in the DB.
Person who build that data insert query, he used javascript to get the time and format it in iso.
Date inside the DB is looks like this "2016-03-17T06:09:21.530Z" and its actual time is "11:39:21 GMT+0530 (India Standard Time)" which is similar to my current time but I'm comparing these two dates as string. and get 1min early data from DB.In that case i can't get an out put because as strings these two aren't match. can anybody recomand a solusion ?
I use OrientDB
Java Code
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
Calendar date = Calendar.getInstance();
long t = date.getTimeInMillis();
date.setTimeInMillis(t);
date.set(Calendar.MINUTE, date.get(Calendar.MINUTE) - 1);
String time1minEarly = df.format(date.getTime());
Using Calendar.set() and Calendar.get() does not modify the date in a way you intend:
This will modify the minutes field in your case. So subtracting "1" will reduce the minute but not give a viable date for cases where minute initially is zero.
You may just subtract a minutes of milliseconds from your "t" variable to get a true minute offset.
And for ease of use you might also consider following advise from #Prashant and using LocalDateTime class from joda library.
Thanks Everybody for your support.
I figure out How to do this. it's pretty easy. Both #rpy and #Prashant are correct. Calendar is not suitable for solve my issue. Also LocalDateTime too. but it did help me to figure out the correct way.
#rpy and #Prashant they both did miss one thing that the javascript time represent the UTC time. that's the issue. (it's 5.5 hours behind compared to my location) so, I figure out this below code. it did what i wanted to do.
It's pretty easy. all you have to do is provide your zone id.
(You can get Zone id using this code : go to the link - http://www.javadb.com/list-possible-timezones-or-zoneids-in-java/)
Also you can choose so many formats by changing "DateTimeFormatter" value.
ZoneId UTCzoneId = ZoneId.of("UTC");
ZonedDateTime time1minEarly = ZonedDateTime.now(UTCzoneId).minusMinutes(1);
String UTCtime1minerly = time1minEarly.format(DateTimeFormatter.ISO_INSTANT);
Out put is similar to this : "2016-03-17T10:39:21.530Z"
(- UTC time at that time : 2016-03-17T10:40:21.530Z)
It appears I can't use the javascript Date object as it inherintly defaults to US dates when you initialise with a datestring. There is no way of passing any culture information to the date object
I.e. No matter what the clients locale settings are
var d = new Date("08/10/2009") will always create a date object representing the 10th August 2009 rather than the 8th October 2009 if the clients locale was the UK.
So given that my requirement is to be able to add/subtract days/months/years easily is there a clever way of doing this easily without the Date object
All i need to do is add a day to a date (or a string representation of a date). so if my code detects the locale setttings are in the US, when it sees a string like "10/08/2009" it whacks it up to "10/09/2009" but if it had detected it was in the UK it would have know it a uk string representation of a date and whacked it up to "09/10/2009"
For date manipulation and localization on JavaScript I always recommend the DateJS library.
This library abstracts the use of Date objects, has a very good localization options, powerful date parsing and formatting, and it also has a very nice fluent API.
If you know you are getting input formatted dd/mm/yyyy you can easily assemble the correct date.
function britDay(D){
D= D.match(/\d+/g);
return new Date(+D[2], D[1]-1, +D[0]);
}
toLocaleDateString will return the date in the format expected by the user.
Relying on the user input that obeys particular formatting rules is optimistic-
which is why most sites use separate, labeled inputs or select fields for the month, date and year.
You probably know that it's easy to add one day to a date, just add 86,400 * 1000 milliseconds to the date. It sounds like displaying in your locale is the issue; does Date.toLocaleString() not do the right thing for you?
dojo.date.locale.parse will be able to parse a formatted string according the locale of your choice. It has a table of cultural data based off unicode.org/cldr. See this article for more information.