i have been tinkering with the date object.
I want to add a dynamic amount of days to a day and then get the resulting date as a variable and post it to a form.
var startDate = $('#StartDate').datepicker("getDate");
var change = $('#numnights').val();
alert(change);
var endDate = new Date(startDate.getFullYear(), startDate.getMonth(),startDate.getDate() + change);
does everything correctly except the last part. it doesnt add the days onto the day
take this scenario:
startdate = 2011-03-01
change = 1
alert change = 1
endDate = 2011-03-11 *it should be 2011-03-02*
thank you to all the quick replies.
converting change variable to an integer did the trick. thank you.
parseInt(change)
just to extend on this: is there a way to assign a variable a type, such as var charge(int)?
You may have fallen victim to string concatenation.
Try changing your last parameter in the Date constructor to: startDate.getDate() + parseInt(change)
See this example for future reference.
convert change to a number before adding it. it looks like you're getting a string concatenation operation rather than the addition you're expectingin your code.
I believe you are concatenating instead of using the mathematical operator. Try this instead,
var endDate = new Date(startDate.getFullYear(), startDate.getMonth(),startDate.getDate() + (+change));
It looks like you are not adding the ending day, you are concatinating it so '1' + '1' = '11'
use parseInt() to make sure you are working with integers
example
var change = parseInt($('selector').val());
Also, with this solution, you could easily end up with a day out of range if you are say on a start date of the 29th of the month and get a change of 5
Related
I'm using the Foundry template on Squarespace and I need to change the date format on post pages from english to portuguese. Instead of "May 6" I need "6 Mai". In Brazil we use the pattern dd/mm/yyyy. In this case I just want the day and month, and also translate all the months (to: Jan, Fev, Mar, Abr, Mai, Jun, Jul, Ago, Set, Out, Nov, Dez).
I already saw people solving this for others languages there. But not to portuguese or on the Foundry template. It's possible to make a code-injection on Squarespace, on the head or footer. I just need a Javascript that can do that, overwriting the theme's default date format.
I would approach it via the following Javascript, inserted via code injection. Note that although some of the month abbreviations are the same, I've included them for clarity and so that it may be more reusable for others. Also, the abbreviations I've used for the keys (that is, the original month abbreviations) may not be what Squarespace actually uses, so they may need to be updated.
<script>
(function() {
var dates = document.getElementsByClassName("dt-published date-highlight");
var newDate;
var i,I;
// Create object with 'source' keys on the left, and 'output' values on the right.
var months = {
"Jan":"Jan",
"Feb":"Fev",
"Mar":"Mar",
"Apr":"Abr",
"May":"Mai",
"Jun":"Jun",
"Jul":"Jul",
"Aug":"Ago",
"Sep":"Set",
"Oct":"Out",
"Nov":"Nov",
"Dec":"Dez"
};
// Loop through all dates, replacing months and reordering display.
// - Trim extra white space from beginning and end of date.
// - Replace multiple consecutive spaces with a single space.
// - Split by space into an array.
// - Replace month text based on 'months' object key:value pairs.
// - Convert array to string, rearranging display order of elements.
// - Set new date HTML.
for (i=0, I=dates.length; i<I; i++) {
newDate = dates[i].innerHTML.trim();
newDate = newDate = newDate.replace(/ +/g, ' ');
newDate = newDate.split(" ");
newDate[0] = months[newDate[0]];
newDate = newDate[1] + " " + newDate[0];
dates[i].innerHTML = newDate;
}
})();
</script>
This is a string 2011-11-09 00:00:00
So now how do I separate the date i.e. 2011-11-09 from the string, I dont want to use the slicing here if anyone has better options or ideas please let me know..
var date = '2011-11-09 00:00:00'.split(' ')[0];
You can split it by ' ' and then the first element will contain what you want.
console.log('2011-11-09 00:00:00'.split(' ')[0]);
Like this:
var date = 'This is a string 2011-11-09 00:00:00'.match(/\d{4}-\d{2}-\d{2}/)
if you dont want to use splicing, like you posted you could create a Date obj
var newDate = new Date(2011-11-09 00:00:00);
then to get the date, just use the toString override
var dateOnly = newDate.toString("YYYY-mm-dd");
That is if you dont want to use splicing or splits
Unlike a vanilla date, a moment does not have any required units that must be passed to its constructor. For instance, this is a perfectly valid way to instantiate a moment, with the unpassed units defaulting to current date and 00:00 time:
moment.utc('07:35', 'HH:mm').toISOString();
> "2013-10-24T07:35:00.000Z" //let's just ignore the timezones for now, ok?
So how can partial moments be merged into one? For instance, I could just .set() first moment's hours to values from the second:
var mergee = moment.utc('07:35', 'HH:mm');
moment.utc('2015-01-01').
set('hours', mergee.get('hours')).
set('minutes', mergee.get('minutes')).
toISOString();
> "2015-01-01T07:35:00.000Z" //yay!
But what if I don't know in advance the format of the "mergee", or even what units it has parsed?
While not entirely supported or recommended, something like this will work:
var m1 = moment.utc('07:35', 'HH:mm');
var m2 = moment.utc('2015-01-01');
var merged = moment.utc(m1._i + ' ' + m2._i, m1._f + ' ' + m2._f);
The space separator isn't necessarily required, but it might prevent conflicts with certain formats.
I could see that you might have troubles though if both moments contained the same elements with different data.
I want to develop a JavaScript function to calculate the activity of users based on the date in the server where the data is stored. The problem is that the date is a string like this:
2013-08-11T20:17:08.468Z
How can I compare two string like this to calculate minor and major time as in the example?
If you want to compare two dates just use this :
var dateA = '2013-08-11T20:17:08.468Z';
var parsedDateA = new Date(dateA).getTime();
var dateB = '2013-06-06T17:33:08.468Z';
var parsedDateB = new Date(dateB).getTime();
if(parsedDateA > parsedDateB) {
// do something
}
Assuming you need to do the comparisons client-side, the best way is to load the dates into Date objects using Date.parse. Then compare them using the functions provided for Date, such as getTime.
Try parse method:
var s = "2013-08-11T20:17:08.468Z";
var d = Date.parse(s);
As I have understood you in the right way, there is a good answer to your question here.
You can also look at this very good Library (DateJS).
If your problem was converting from the Date-String to js-Date look at this Page.
Hi this is making me nuts. I am not a developer. Trying to get this to work.
User puts in a date (hire date) into form using Date object (calendar)
Next field should take that date and subtract todays date to get the length of employment.
But I get undefined in the field AND my original hire date disappears.
Here is what I have, help please, much appreciation!
//grab date of hire
try{document.getElementById("dData_DOH").onchange = custom_calculateDate;}catch(e){}
//not sure if necessary - field that the difference should go to
try{document.getElementById("dData_LengthEmp").onblur = insertDate;}catch(e){}
//Function to grab input hire date
//Create variable for now
//Create variable for difference
function custom_calculateDate(){
var hireDate = document.getElementById("dData_DOH").value = "";
var timeNow= new Date();
var diff = Math.abs(timeNow - hireDate);
document.getElementById("dData_DOH").setAttribute('value', custom_calculateDate());
}
//Function to get the difference into the LengthEmp field
function insertDate() {
document.getElementById("dData_LengthEmp").setAttribute("", custom_calculateDate());
}
I know this is completely wrong, as I said I am not a developer or programmer, I cannot figure out how to get this information into this field and get my original field to still show.
Thank you for reading this!
Use value instead of setAttribute
document.getElementById("dData_DOH").value = custom_calculateDate();
Wow wow wow.
I'll try to rewrite your code by giving you explainations about why:
// Firstly, the onchange event doesn't work on IE for text inputs, prefer onblur
document.getElementById('dData_DOH').onblur = function(e) {
// Now let's get some variables
var hireDate = this.value, // "this" refers to the element that triggered the event
now = new Date(),
// You were on the right track for the difference, almost!
diff = Math.abs(new Date(now.getTime() - hireDate.getTime()))
// Finally, just don't change the original field, but the one you wanted to modify
document.getElementById('dData_LengthEmp').value = diff.toTimeString() // Get the time as a readable format
}
I haven't tested the solution, but it should get you on the track.
Btw, don't use try/catch.