how to find hh:mm:dd difference between two strings in Javascript - javascript

In my app I have two date strings:
Say that they are:
date1 = "2014-03-14 18:25:15";
date2 = "2014-03-14 16:26:15";
I get these date strings based on two events that the customer selects. Now I need to show the difference between these two strings in HH:MM:DD format.
What I am currently doing is, posting to PHP using AJAX and then doing the calcuation in the server:
$rDate = new DateTime($date1);
$tDate = new DateTime($date2);
$interval = date_diff($rDate,$tDate);
echo $interval->format('%h:%i:%s');
Then in the AJAX response handler I print it to a div
My problem is that server trip is just too much an overkill for this. How can I achieve the same thing from browser itself? (Javascript/Jquery/MomentJS)...
Any help is greatly appreciated!

I'd suggest looking into Moment.js, which is a very well featured date handling library for Javascript.
Here's the relevant manual link for Moment.js for what you're wanting to do: http://momentjs.com/docs/#/displaying/difference/
Hope that helps.

Related

date and time picker with validation [duplicate]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 9 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
I've been looking around for a decent jQuery plugin that can handle both dates and times. The core UI DatePicker is great, but unfortunately I need to be able to take time in as well.
I've found a few hacks for the DatePicker to work with times, but they all seem pretty inelegant and Google isn't turning up anything nice.
Is there a good jQuery plugin for selecting dates and times in a single UI control with a usable interface?
By far the nicest and simplest DateTime picker option is http://trentrichardson.com/examples/timepicker/.
It is an extension of the jQuery UI Datepicker so it will support the same themes as well it works very much the same way, similar syntax, etc. This should be packaged with the jQuery UI imo.
#David, thanks for the recommendation! #fluid_chelsea, I've just released Any+Time(TM) version 3.x which uses jQuery instead of Prototype and has a much-improved interface, so I hope it now meets your needs:
http://www.ama3.com/anytime/
Any problems, please let me know via the comment link on my website!
In my view, dates and times should be handled as two separate input boxes for it to be most usable and efficient for the user to input. Let the user input one thing at a time is a good principle, imho.
I use the core UI DatePicker, and the following time picker.
This one is inspired by the one Google Calendar uses:
jQuery timePicker:
examples: http://labs.perifer.se/timedatepicker/
project on github: https://github.com/perifer/timePicker
I found it to be the best among all of the alternatives. User can input fast, it looks clean, is simple, and allows user to input specific times down to the minute.
PS:
In my view: sliders (used by some alternative time pickers) take too many clicks and require mouse precision from the user (which makes input slower).
My best experience with a datepicker is with the prototype-based AnyTime. I know that's not jQuery, but it may still be worth the compromise for you. I know absolutely no prototype, and it's still easy enough to work with.
One caveat I've found: it is not forward compatible on some browsers. That is, it did not work with a newer version of prototype on Chrome.
Just to add to the info here, The Fluid Project has a nice wiki write-up overviewing a large number of date and/or time pickers here.
I researched this just recently and have yet to find a decent date picker that also includes a decent time picker. What I ended up using was eyecon's awesome DatePicker, with two simple dropdowns for time. I was tempted to use Timepickr.js though, looks like a really nice approach.
I have ran into that same problem. I actually developed my using server side programming, but I did a quick search to try and help you out and found this.
Seems alright, didn't look at the source too much, but seems to be purely JavaScript.
Take look:
http://www.rainforestnet.com/datetimepicker/datetimepicker.htm
Here is the demo page link:
http://www.rainforestnet.com/datetimepicker/datetimepicker-demo.htm
good luck
This is some code I use to have a user select one
datetimepicker, set the datetime, and have the
other datetimepicker add One Minute to that time.
I needed this for a custom medication control....
Anyway, thought it might help someone else since I could
not find the answer any where online...
(at least not a complete answer)
Keep in mind that the 60000 added, adds one minute.
(60 * 1000 milliseconds)
$('.frdtPicker').datetimepicker({
onClose: function(dateText, inst) {
var endDateTextBox = $('.todtPicker');
if (endDateTextBox.val() != '') {
var testStartDate = new Date(dateText);
var testEndDate = new Date(endDateTextBox.val());
if (testStartDate > testEndDate) {
var testStartDate = new Date(dateText).getTime() + 60000;
var testStartDate2 = new Date(testStartDate);
endDateTextBox.datetimepicker('setDate', (new Date(testStartDate2)));
}
}
else {
var testStartDate = new Date(dateText).getTime() + 60000;
var testStartDate2 = new Date(testStartDate);
endDateTextBox.datetimepicker('setDate', (new Date(testStartDate2)));
}
$('.frdtPicker').val(dateText); //endDateTextBox.val());
},
onSelect: function(selectedDateTime) {
var start = $(this).datetimepicker('getDate');
$('.todtPicker').datetimepicker('option', 'minDate', new Date(start.getTime()));
}
});
Take a look at the following JavaScript plugin.
Javascript Calendar with date and time
I've made it to be simple as possible. but it still in its early days.
Let me know the feedback so I could improve it.
Not jQuery, but it works well for a calendar with time: JavaScript Date Time Picker.
I just bound the click event to pop it up:
$(".arrival-date").click(function() {
NewCssCal($(this).attr('id'), 'mmddyyyy', 'dropdown', true, 12);
});
I make one function like this:
function getTime()
{
var date_obj = new Date();
var date_obj_hours = date_obj.getHours();
var date_obj_mins = date_obj.getMinutes();
var date_obj_second = date_obj.getSeconds();
var date_obj_time = "'"+date_obj_hours+":"+date_obj_mins+":"+date_obj_second+"'";
return date_obj_time;
}
Then I use the jQuery UI datepicker like this:
$("#selector").datepicker( "option", "dateFormat", "yy-mm-dd "+getTime()+"" );
So, I get the value like this: 2010-10-31 12:41:57
We had trouble finding one that worked the way we wanted it to so I wrote one. I maintain the source and fix bugs as they arise plus provide free support.
http://www.yart.com.au/Resources/Programming/ASP-NET-JQuery-Date-Time-Control.aspx

Date presentation with AngularJS - how costly is a filter?

I think the angular date and currency filters are really slick, but I've read some commentary online saying that filters negatively impact performance. I'm working on an enterprise app that will be handling all different types of date objects, and we want to render the formatting differently based on user settings.
Based on what I've read, using the filter directly in the DOM is not the best approach, so I'm thinking I'll extract it to a service. The angular documentation leaves so much to be desired, as you know, and there seem to be a lot of different ways to accomplish this.
Ultimately I just want to use angular's built in date filter for presenting a variety of date formats coming from payloads on various pages to format that date. Furthermore, we have independent user settings for both date and time. The options for date formatting are: MM/dd/yyyy and dd/MM/yyyy. The options for time formatting are: HH:MM:SS and H:MM:SS A
I am leaning toward using the built in date filter in a service. I think the ideal answer would just need to contain a bit of pseudocode to get me going. Thanks in advance for your time.
Also - please let me know if you need more info or any code. Not sure what to include here...
I figured out what I was doing wrong with my first attempt. In case anyone else is looking for this topic, here's the code:
app.service('DateTimeService', ['$filter', function ($filter) {
var self = this
init()
return self
function init () {
self.formatter = $filter('date')
self.formatDate = formatDate
self.formatTime = formatTime
}
function formatDate (time) {
return self.formatter(time, settings.dateFormat)
}
function formatTime (date) {
return self.formatter(date, settings.timeFormat)
}
}])
// in the controller
DateTimeService.formatDate(dateObject)

Dates - JavaScript and C#

I hate dates, I can never get them to behave.
I have a javascript variable that looks like this:
var currentDate = new Date();
I pass this to a C# Web API controller as a parameter.
My local time was 12:43 but when I put a breakpoint in my action it shows 11:43. The problem is, that if I do this at 00:43 then my controller would take the date as yesterday. I need it to pick out the right day. If I select the currentDate as 02/09/2015 12:43 then I need my controller to use the same date.
I know this has something to do with local times etc, but how can I get them all to use the same one?
Any help would be greatly appreciated.

What is the scope of moment.tz.setDefault() when used in Meteor?

TL;DR What is the scope of moment.tz.setDefault()?
I'm sure my problem here stems from my inexperience with both JavaScript and Meteor but I've been struggling with the problem for several straight days now.
I'm working on an app that must take into account the client's timezone but I'm having significant difficulty in forcing the server code to use the client's timezone. Somewhere along the way--that being from the moment the client presses "Submit" to the moment Meteor inserts--my timezone setting is getting lost and local time (of the server) is being used.
The app flow is like this:
(client) user submits form
(client) validation of data is performed
(server) Meteor method is called
(server) validation of data is performed (same code as earlier)
(server) business logic is applied
(server) insert into DB
I capture the timezone at step 1 and try to pass it along through all the steps but I must be missing something because between 4 and 5 the timezone is (seemingly) lost. The fast is, I'm not seeing why. I've checked this 100 times and tried all manner of different permutations but can't figure out where the gap is (I've used soooo many console.log()s it's crazy.)
So instead of trying to set the timezone at every point Moment() is used (because it defaults to calculating in local time) I discovered moment.tz.setDefault() and tried using that at least once on each .js file in my app. But it didn't work.
Reading this it might sound like I'm not doing enough testing but that is not the case. I have spent 10s of hours on this and I'm just not getting it. I'd love to share the code but I think it's just too long and complicated to properly share so I've done my best to explain the problem.
Good news! You're overcomplicating it :-)
Open up a browser console & type time = new Date(). Notice how it's in the correct timezone? That's because the timezone conversion is happening on the client.
Now, type time.valueOf(). As you probably know, you've got the number of milliseconds since 1-1-1970...but in what timezone?? You guessed it, UTC!
So if all you're doing is saving a number, and the client is fully capable of converting that number into the local timezone, why not save the time in UTC on the server? You'll get an ISODate() in your database (which is a fancy int64). Then, when you retrieve it on the client, you can put it in their local time (they might be traveling!) or any other timezone you chose. If it's a meetup in a certain city, simply grab the timezone of that city & apply it to the field. Hint: THIS is the appropriate time to use moment.js, not before!
Edit for time patterns:
Based on the new info, I imagine you have something that accepts an arrivalTime & then makes sure the time is between an earlyArrival and lateArrival say, 7:00 - 8:30AM. So, save the times as dates
timeToDate = function(time) {
return new Date('1970 1 1 ' + time);
};
earlyArrival = timeToDate('7:30 AM');
arrivalTime = timeToDate('8:00 AM');
lateArrival = timeToDate('8:30 AM');
Then, validate via simple math: earlyArrival < arrivalTime.
OR, if you use simple schema (which you should), a validation pattern might look like this:
departureTime: {
type: Date,
min: timeToDate('5:00 PM'),
max: timeToDate('6:30 PM'),
autoValue: function() {
return timeToDate(this.value);
},
custom: function () {
if (this.value < this.field('arrivalTime').value) {
return "lateAfterEarly";
}
}

Show date with format

I have:
var date = new Date();
and i have many formats:
var one = 'yy-mm-dd';
var two = 'dd.mm.yy';
var three = 'dd/mm/yy';
var four = 'mm/dd/yy';
Is possible to showing current date with this four formats? I know - i can use clause IF or SWITCH and set this, but maybe in JavaScript or jQuery without external libraries i can use this format as option?
If you're also already using jQuery UI, there's a string formatter function in the DatePicker.
If not, use Datejs.
You will have to do it yourself by using getFullYear(), getMonth() and getDate() and combining them as you see fit (no jquery/jquery UI required).
If you are using or can use JQuery UI you can take advantage of the $.datepicker.formatDate method (that's the approach we took).
Your question has been asked (in a somehow different form) before

Categories

Resources