How to find the duration between dates? - javascript

I have the date as 07/24/2012 and the time as 23:59:59 in separate variables. Using moment.js I am trying to find the number of days/hours/minutes between this and the current date.
How can this be done with moment.js?

Assuming $date holds "07/24/2012" and $time holds "23:59:59"...
moment($date + " " + $time, "MM/DD/YYYY HH:mm:ss").fromNow();
The + operator concatenates the strings which form a value that moment can parse directly.
Reference:
Moment parsing
Moment time from now

moment.js doesn't provide a "direct" way to perform this task as fromNow likes to get clever and likes to use humanize; however (using from in the moment.js source as inspiration) we can derive a little solution:
var whence = moment("2040-11-28")
var remaining = moment.duration(whence.diff(moment()))
Then to use/format the duration (sadly, there is no duration.format() available):
var r = remaining
var str = Math.floor(r.asDays()) + "." + r.hours() + ":" + r.minutes() + ":" + r.seconds()
alert(str)
PaulProgrammer's answer provides a nice solution on how how to get the date initially from the two separation values. Alternatively (since Moment.js 2.1.0), the date-time can be obtained through:
var whence = moment(yourDate, "MM/DD/YYYY").add(moment.duration(yourTimeOfDay))

Related

Date and time parsing in JavaScript

I have a question that I am trying to solve for whole day.
I have Date and Time from Oracle DB that is shown on html page. I have jstl date formatter that has special pattern to show it. Let's take an example 09.05.2017 17:35 +0500 and pattern MM.dd.yyyy HH:mm Z. And I am getting it as String with jQuery . The first case: how to convert it to Date type without any changes. I tryed var date = new Date('09.05.2017 17:35 +0500') but if I have another time zone I'll recieve another UTC and time(hour) or maybe month etc.
Second: how to convert this time to UTC+0300.
I know one solution of this cases, but I think it's not easy. As I have constant pattern of Date, I can always parse the string and to write huge logic for solving second case. I am bad in JS and will be grateful for solution.
Regarding the parsing question, that is answered at Why does Date.parse give incorrect results? The bottom line is that you should parse the string manually and not rely on the built-in parser. A library can help, but if you only have one or two formats to deal with, writing your own parser isn't too difficult.
As for presenting time in a particular timezone, the same advice applies. If you always want UTC+0300, then start by knowing that javascript Dates are always UTC internally and have UTC methods to access those values. So you just change the UTC time by the required offset and format the date as required.
For formatting, see Where can I find documentation on formatting a date in JavaScript?
An example of adjusting the timezone:
// Return a string for UTC+0300 for the supplied date
// in dd-mm-yyyy hh:mm:ss format
function getUTC03(date) {
// Helper to pad with leading zero
function z(n){return ('0'+n).slice(-2)}
// Copy the date so don't affect original
var d = new Date(+date);
// Set UTC time to required offset
d.setUTCHours(d.getUTCHours() + 3);
// Format using UTC methods
return z(d.getUTCDate()) + '-' +
z(d.getUTCMonth()+1) + '-' +
d.getUTCFullYear() + ' ' +
z(d.getUTCHours()) + ':' +
z(d.getUTCMinutes()) + ':' +
z(d.getUTCSeconds()) + ' ' +
'+0300';
}
console.log('Currently at +0300 it\'s ' + getUTC03(new Date()));
However, many places observe daylight saving. To adjust for that, a library is helpful. You just need to provide a location for which the offset can be determined for any particular date and time. Again, there are many questions here about that too.

Convert Date String(yymmdd) to Date Object in JS

I have a date string in "yymmdd" format i want to convert it into date object in JS
the input string is "161208"
I have tried code below
var mydate = new Date(InputDate);
but it says invalid date.
Here is the fiddle
https://jsfiddle.net/4ry0hL4t/
the basic need is that, I have a date string in "yymmdd" format and i have to convert it to different date formats like ("yyyy/mm/dd, yy-mm-dd","yy/mm").
Check my answer.
Basically you first need to give a proper format to your string. You can either do it manually or use moment.js.
stringFormat = moment(dateObject).format("YYYY-MM-DDTHH:mm:ss");
date = new Date(stringFormat);
This is also really helpful to understand how the different string formats are compatible with different browsers.
I'm not sure if this is what you're after?
var s = '161208';
var dt = new Date('20' + s.substring(0, 2) + '-' + s.substring(2, 4) + '-' + s.substring(4));

Getting next day date for specific string format in Google Apps Script (JavaScript)

Good day everyone!
Working on aprojectmI had to start working with Google Spereadsheet interface and faced a problem I cannot quickly overcome due to not working with JavaScripts ever before.
I have a date in specific format as a string
var date = "2012-08-09";
What I need is to get the next day date as
date = "2012-08-10";
which should include changing not only the day, but month and year too, if necessary.
I've tried using date format
var datum= new Date(date);
datum.setDate(datum.getDate() + 1);
date = datum.toString('yyyy-MM-dd');
but the code appears to fail at writing date to datum variable.
What is the best and quickiest way tosolve this litle problem?
Thanks
The problem when you tag a question 'Javascript' and when you are actually using Google Apps Script is that you get nice answers from people that do not know some special functions available in GAS.
GAS is based on Javascript but Javascript is not GAS... if you see what I mean ;-)
That said, there is actually a "special" function to format date string and I'll show it in the following code.
But there is also another point that could put you into trouble : if you don't mention hours in your date object there is a risk to shift one day if you live in a country that uses daylight savings. This issue has been discussed quite often on this forum and elsewhere so I won't give all the details but it's a good idea to take this into account when you play with date objects. In the code below I extract a tz (time zone) string from the date object we have just created to know if it's in summer or in winter time, then I use this tz string as a parameter in the Utilities.formatDate() method . This guarantees an exact result in every situations.
Here is (finally) the test code :
(use the logger to see results. script editor>view>logs)
function test(){
date = "2012-08-9";
var parts = date.split('-')
var datum = new Date(parts[0],parts[1]-1,parts[2],0,0,0,0);// set hours, min, sec & milliSec to 0
var tz = new Date(datum).toString().substr(25,8);// get the tz string
Logger.log(datum+' in TimeZone '+tz)
datum.setDate(datum.getDate() + 1);// add 1 day
var dateString = Utilities.formatDate(datum,tz,'yyyy-MMM-dd');// show result like you want, see doc for details
Logger.log(dateString);// the day after !
}
Logger results :
Thu Aug 09 2012 00:00:00 GMT+0200 (CEST) in TimeZone GMT+0200
2012-Aug-10
It sounds like a parsing problem you may have better luck, splitting out the date and putting the parameters in individually, any errors you get would be useful:-
var parts = date.split("-");
var datum = new Date(
parseInt(parts[0], 10),
parseInt(parts[1], 10) - 1,
parseInt(parts[2], 10));
There is no built in formatting function for the JavaScript Date object, I'm not sure if the google apps api is any different though. To perform the last line of your code you may either need to write your own functions to extract the data from the JavaScript date object and format it, hint you will also need to write a zerofill function if you want to ensure two digits in your date and month parts of the output.
var formatted = datum.getFullYear() + "-" +
zerofill(datum.getMonth() + 1, 2) + "-" +
zerofill(datum.getDate(), 2);
Passing a format string to toString works in .NET, and it may work in Java, however this doesn't work in Javascript.
Try the following,
var date = "2012-08-09";
var datum = new Date(date);
datum.setDate(datum.getDate() + 1);
date = datum.getFullYear() + "-" + (datum.getMonth() + 1) + "-" + datum.getDate();
Try the following in http://jsfiddle.net/ It works.....
<html>
<head>
<script>
function foo(){
var date = "2012-08-09";
var datum = new Date(date);
datum.setDate(datum.getDate() + 1);
date = datum.getFullYear() + "-" + (datum.getMonth() + 1) + "-" + datum.getDate();
document.getElementById("demo").innerHTML = date;
}
</script>
</head>
<body onload="foo()">
<p id=demo></p>
</body>
</html>​

date string formatting

The best way to take a string that is formated like...
YYYY-MM-DD
and make it appear like...
MM/DD/YYYY
The reason it is not a javascript date object is because I am working with massive amounts of data and these dates are being pulled from a database.
I see no need to convert it to a date object.
How about:
s.substr(5,2) + '/' + s.substr(8) + '/' + s.substr(0,4)
You can use a regular expression in JavaScript (assuming JS because your question is tagged as such):
var date = "2010-05-09";
var formatted = date.replace(/([0-9]{4})-([0-9]{2})-([0-9]{2})/, "$2/$3/$1")
What I like about this more than using substring is that it seems more apparent what is being done.
If you replace the dashes with slashes it will parse, then you can use the date functions to get the various components (or convert to string using one of the various toString() functions).
var date = new Date( Date.parse( old.replace(/-/g,'/') ) );
alert( date.getMonth() + '/' + date.getDate() + '/' + date.getFullYear() );
This has the advantage of being able to use the date as a date for calculations, not merely doing string formatting. If string formatting is all you need AND your date strings are always valid, then using #Guffa's substr method is probably the best way to handle it.
By brute force you could do something like:
var old = '2010-02-03'.split('-');
var desired = old[1] + '/' + old[2] + '/' + old[0];
Saves the hassle of working with Date object.

Formatting the Date in JavaScript

Using newDate() function in Java script, I am able to get today's date. I am getting the date in the format 3/3/2009 (d/m/yyyy). But i actually need the date in the format 2009-03-03 (yyyy-mm-dd). Can anyone pls let me know how to format the date as i require?
You usually have to write your own function to handle the formatting of the date as javascript doesn't include nice methods to format dates in user defined ways. You can find some nice pieces of code on the net as this has been done to death, try this:
http://blog.stevenlevithan.com/archives/date-time-format
Edit: The above code seems to be really nice, and installs a cool 'format' method via the date object's prototype. I would use that one.
If you want to roll-your-own, which is not too difficult, you can use the built-in javascript Date Object methods.
For example, to get the current date in the format you want, you could do:
var myDate = new Date();
var dateStr = myDate.getFullYear +
'-' + (myDate.getMonth()+1) + '-' + myDate.getDate();
You may need to zero-pad the getDate() method if you require the two-digit format on the day.
I create a few useful js functions for date conversions and use those in my applications.
There's a very nice library to manage date in JS.
Try this.
You'll pretty much have to format it yourself, yeah.
var curDate = new Date();
var year = curDate.getFullYear();
var month = curDate.getMonth() + 1;
var date = curDate.getDate();
if (month < 10) month = "0" + month;
if (date < 10) date = "0" + date;
var dateString = year + "-" + month + "-" + date;
It's a bit long, but it'll work (:
add jquery ui plugin in your page.
function DateFormate(dateFormate, dateTime) {
return $.datepicker.formatDate(dateFormate, dateTime);
};
Just another option, which I wrote:
DP_DateExtensions Library
Not sure if it'll help, but I've found it useful in several projects.
Supports date/time formatting, date math (add/subtract date parts), date compare, date parsing, etc. It's liberally open sourced.
No reason to consider it if you're already using a framework (they're all capable), but if you just need to quickly add date manipulation to a project give it a chance.

Categories

Resources