Date formating issue when using momentjs and bootstrap calendar - javascript

I have a function that return an array of objects that is used as parameter for a bootstrap calendar. The problem is when i create event_data.start. If i use start_date.year() in the end the calendar will not work because of invalid date. If I put 2013 (or any integer), then it works.
I used a breakpoint at that line, start_date.year() always return 2013.
var start_date = moment(reminder.start_date);
var stop_date = moment(reminder.stop_date);
var reminder_time = moment(reminder.time, 'HH:MM:ss');
while (start_date.unix() < stop_date.unix()) {
start_date = moment(start_date.year()+ '-' + start_date.month().toString() +'-'+start_date.add('days', 1).date());
event_data.start = new Date(parseInt(start_date.year()), 9, 25 - 3, 16, 0);
events_array.push(event_data); //events_array then used for calendar
}
I am thinking the start_date object is used as some kind of reference and the actual value is not passed or something. Hope you can give me an idea.

You are doing entirely too much manual string manipulation in this code. If you're using moment.js, then you should work with the API instead of working against it. Try something like this:
while (start_date.isBefore(stop_date)) {
start_date.add('days', 1);
event_data.start = start_date.clone().toDate();
events_array.push(event_data);
}
I used .clone() because I'm uncertain how you will be using the date in your object. You may find that it is not necessary depending on what you are doing.
Then there's some weirdness in your code to deal with. First, you define reminder_time but don't use it for anything, so I'm not sure why it is there.
Then, you had this line:
event_data.start = new Date(parseInt(start_date.year()), 9, 25 - 3, 16, 0);
That would be only using the year part of the start_date and hard-coding the rest to October 22 16:00. I'm not sure why at all you would do that, so I omitted it from the above code. If that's actually what you wanted to do, then do it like this instead:
event.start = start_date.clone().month(9).date(22).startOf('day').hour(16).toDate();
Here you definitely need to use .clone() because otherwise the manipulation of value would interfere with your loop logic.

Related

SharePoint/Javascript: comparing calendar date times in javascript

I am trying to find the best approach to comparing date/times using Javascript in order to prevent double booking on a SharePoint calendar. So I load an array with items that contain each event, including their start date/time and end date/time. I want to compare the start date/time and end date/time against the start/end date/times in the object, but I am not sure how to ensure that dates will not lapse.
like:
//date that is created from user controls
var startDate = new Date(startDat + 'T' + startHour + ':' + startMin + ':00');
var endDate = new Date(endDat+ 'T' + endHour+ ':' + endMin+ ':00');
for ( var i = 0; i < allEvents.length; i++ ) {
var thisEvent = allevents[i];
//having trouble with the compare
//i have tried silly ifs like
if (thisEvent.startDate >= startDate && thisEvent.endDate <= endDate) {
// this seems like I am going down the wrong path for sure
}
}
I then tried breaking apart the loaded object into seperate values (int) for each component of the date
var thisObj = { startMonth: returnMonth(startDate), startDay: returnDay(startDate), etc
but I am not sure this isn't just another silly approach and there is another that just makes more sense as I am just learning this.
I have a similar requirement in progress but chose to solve it at the booking stage, with jQuery/SPServices.
The code is still in build (ie not finished) but the method may help.
I attach an event handler to a column, then on selection, fetch all the dates booked in the same list to an array, then display that array on a rolling 12 month cal, as below.
I'm not checking to ensure a new booking doesn't overlap but a quick scan through the array on Pre-Save would provide a strict Go/No Go option for me. Relies on client side JS though, so not going to work in a datasheet or web services context.

Javascript prototype function: decimal time value to a time string

On a project I'm currently working on in JavaScript, I'm using decimal formats so it's easier to calculate with rather than using an hour/minute format in strings (calendar related project). To display the time on the user's screen though, the timecode has to be shown as hh:mm.
I thought it would be great to use a String prototype function for this as it would allow me to use code like:
var time = 8.75;
document.write("Meeting at "+time.toTime()); // writes: Meeting at 8:45
So far, I've got that almost working, using:
String.prototype.toTime = function(){
var hrs = this.toString().slice(0,this.indexOf("."));
var min = Math.round(this.toString().slice(this.indexOf("."))/100*60);
min = min<10 ? "0"+min : min.toString();
return hrs+":"+min;
}
The problem, though, is that this will only work if the variable time is a string. Otherwise it will give an undefined error.
Would there be any way of applying the prototype to a different object in JavaScript, so that I don't have to use time.toString().toTime()?
Thanks!
Firstly, you can add to the Number prototype. Many people will warn against modifying prototypes, which in many cases is justified. If there is a chance 3rd party scripts will be running alongside yours, it is a danger to modify prototypes.
Secondly, I simplified your code a little, using modulus, and floor to calculate the hrs and mins...
Number.prototype.toTime = function(){
var hrs = Math.floor(this)
var min = Math.round(this%1*60)
min = min<10 ? "0"+min : min.toString();
return hrs+":"+min;
}
var time = 8.25;
console.log("Meeting at "+time.toTime());
You can use Object.prototype.toTime.

Javascript Date() parameters for constructor

Let's say I want to create a date-object for 2012 Sep 1st, 10:11:15 h.
I figured out:
past = new Date(2012,08,01,10,11,15);// works!
past = new Date('2012,08,01,10,11,15');// doesn't work.
The problem is, I want to use it in combination with a method:
past = new Date(mypastformatfunc(mystring_to_format));
This gives me NaN. No valid Date-object created.
I checked the return of the mypastformatfunc() and it seems I have the right format. Is there any escaping problem regarding quotes?
How can I get this to work? It's really strange...
Thanks.
EDIT SOLVED:
Problem was it wasn't a one value but single parameters. They can't be passed by a function's return at once....
Use the date string as the parameter to the constructor.
past = new Date('2012,08,01,10,11,15'.replace(/(\d+),(\d+),(\d+),(\d+),(\d+),(\d+)/, '$1/$2/$3 $4:$5:$6'));
function mypastformatfunc(str) {
return str.replace(/(\d+),(\d+),(\d+),(\d+),(\d+),(\d+)/, '$1/$2/$3 $4:$5:$6')
}

JavaScript - Compare two timestamps

i try to compare two timestamps like this:
var nowDate = new Date();
var givenDate = new Date(parseInt(year), parseInt(month), parseInt(day), parseInt(hour), parseInt(minute), 0);
var nd_timestamp = nowDate.getTime();
var gd_timestamp = givenDate.getTime();
if (nd_timestamp > gd_timestamp) {
alert("yes");
}
But it is not working properly. If i look at the nd_timestamp and gd_timestamp everything looks fine, but the if-clause is not working. If i remove the parseInt(year)... and enter Date(2012, 04, 20, 0, 0, 0) the if-clause is working.
The variables year, month etc. comes through a function, but if i debug it with alert(year) etc. everything is fine. The given date through the form is smaller than the actual date.
Does anybody know why it is not working with variables?
Thanks!
You should check the values you pass to the Date constructor for validity, which includes explicitly specifying 10 as the second parameter to all of your parseInt calls to avoid nasty surprises.
Regarding the second parameter, the documentation says
While this parameter is optional, always specify it to eliminate
reader confusion and to guarantee predictable behavior. Different
implementations produce different results when a radix is not
specified.
You have to take 1 from Month because for some reason it is zero based, unlike the others.

String operations in Vista/W7 gadget's javascript

I experimenting with writing Vista/W7 gadgets. In my experiment I want to write the modification date of certain files on the system. Problem is that if I want use string manipulation functions the gadget just stops writing its output. Part of the gadget's code looks like this:
function format_lmd(lmd)
{
// Parse something like "Sun Aug 26 17:13:22 UTC+0200"
var lmdFields = lmd.split(' ');
//weekday = lmdFields[0];
//month = lmdFields[1];
//monthday = lmdFields[2];
//moment = lmdFields[3];
//return monthday+' '+month+' '+moment;
return lmd;
}
function paintGadget()
{
var fileitem = System.Shell.itemFromPath("c:\\myfile.txt");
//canvas.addTextObject(' '+fileitem.modifyDate, 'Segoe UI', 9, 'white', text_offset, 21);
var result = null;
result = ' ';
result += format_lmd(fileitem.modifyDate);
canvas.addTextObject(result, 'Segoe UI', 9, 'white', text_offset, 21);
}
The call to split (in the function format_lmd) seems to halt the script (or better: throw an exception). Although documentation seems to indicate that the split function can be used to split a string in multiple parts, it doesn't work in my case.
Questions:
How should I correctly use the split method?
I didn't use Javascript before so when to declare a variable with "var" and when not remains a mystery for me. Is there a good introduction to Javascript that can be used for gadgets?
What is the best way to debug a gadget?
Thanks,
Patrick
EDIT: I found out how to enable the debugger for Javascript (see http://msdn.microsoft.com/en-us/library/bb456467%28v=VS.85%29.aspx#_sidebar_overview_debugging_basic). A debug window now pops up and says "Object expected", but this doesn't really help me.
This is one of the major issues with the Windows Desktop Gadgets API and System.Shell namespace. Some of the commands return types that aren't handled natively by JScript. Fortunately, this isn't one of those times but the issue is similar. I'll get to the answer, but first, a bit of side-note rambling.
You noticed when checking typeof lmd in the function, "date" is the result. What's strange about this is that there is no native date type JScript/ECMAScript - typeof new Date() will result in "object". The reason for this is that many System.Shell.* methods are mapped to the .net equivalent methods and the result is just returned to the JScript with no effort to convert the data into a JScript native type. A very short-sighted implementation by Microsoft.
When outputting lmd to a debugger you'll see a string result, something like:
Wed Nov 25 11:06:30 UTC 2009
This is because a function that expects a string will convert a non-string argument to a string. System.Debug.outputString() is no exception here. Realizing this, the solution becomes clear - force the type conversion from "date" to a string:
var lmdFields = String(lmd.split(' '));
// or
var lmdFields = (lmd+"").split(' ');
//-> ["Wed","Nov","25","11:06:30","UTC","2009"]
If you want to convert the date to a JavaScript Date object, you can just pass it to the Date() constructor:
var lmdFields = new Date(lmd);
System.Debug.outputString(lmdFields.toLocaleString());
//-> "25 November 2009 11:06:30"
If its a Date then maybe this will help (not tested, but a guide)...
function format_lmd(lmd)
{
month = lmd.getMonth()+1; // returns numeric value
monthday = lmd.getDay(); // 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on
// not sure what you mean for 'moment'?
return monthday+' '+month+' '+moment;
}
You could provide month and day values in an array and just look them up if you wanted.
Reference:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date#Methods

Categories

Resources