JavaScript Date() formatting and calculations - javascript

I want to get date from input which format is dd-mm-yyyy when this is set via Bootstrap Date Picker and base on this date calculate end of the week. Somehow I get some weird results.
$('#date-start').on('changeDate', function(){
var objThs = $(this);
if(objThs.parent().is('.reportDateWeeks')){
var arrDateEl = objThs.val().split("-"),
datStartDate = new Date(arrDateEl[2], arrDateEl[1] -1, arrDateEl[0]),
datEndDate= new Date(datStartDate.setDate(datStartDate.getDate()+7)),
datEndDateFormated = datEndDate.getDate() + '-' + datEndDate.getMonth() + 1 + '-' + datEndDate.getFullYear();
console.log('start ' + objThs.val());
console.log('end' + datEndDateFormated);
}
});
e.g. if I chose 04-05-2014 then console returns me:
start 04-05-2014
end 11-41-2014

I see two problems.
You switched month and day in the result.
You should add parentheses around datEndDate.getMonth() + 1. Otherwise the 1 will be added as a string, not a number (producing the 41 in your example).
So the fixed could would look like:
var datEndDateFormated = (datEndDate.getMonth() + 1) + '-'
+ datEndDate.getDate() + '-'
+ datEndDate.getFullYear();

Ok I found solution...
datEndDateFormated = datEndDate.getDate() + '-' + datEndDate.getMonth() + '-' + datEndDate.getFullYear();
I was so blind.. sory about that

Use parseInt method to convert string to integer and then +1 to it.
datEndDateFormatted = datEndDate.getDate() + '-' + parseInt(datEndDate.getMonth() + 1) + '-' + datEndDate.getFullYear();

Related

Javascript: convert datetime to DD/MM/YYYY - Time?

I have a datetime that looks like this:
2017-04-17 18:26:03
How can I convert this to this format using javascript or jquery:
17/04/2017 18:26
I found this question which I thought might help me but the answers are converting a timestamp but mine is not a time stamp.
How to convert a DateTime value to dd/mm/yyyy in jQuery?
You can use simple string and array manipulation.
const dateTime = '2017-04-17 18:26:03';
const parts = dateTime.split(/[- :]/);
const wanted = `${parts[2]}/${parts[1]}/${parts[0]} ${parts[3]}:${parts[4]}`;
console.log(wanted);
Additional: If you don't have an environment that supports Template Literals then you can write it like this.
const dateTime = '2017-04-17 18:26:03';
const parts = dateTime.split(/[- :]/);
const wanted = parts[2] + '/' + parts[1] + '/' + parts[0] + ' ' + parts[3] + ':' + parts[4];
console.log(wanted);
You could use a regular expression within a replace call:
input.replace(/^(\d+)-(\d+)-(\d+)(.*):\d+$/, '$3/$2/$1$4');
var input = '2017-04-17 18:26:03';
var result = input.replace(/^(\d+)-(\d+)-(\d+)(.*):\d+$/, '$3/$2/$1$4');
console.log(result);
Explanation
^: match start of the string.
(\d+): capture group that matches digits. A captured group can be back-referenced with $1 for the first group, $2 for the second ... etc. in the second argument.
:\d+$: match a colon followed by digits and the end of the string ($): as this is not captured, this part (seconds) will be omitted in the result.
try to create a function that format your date. here is an example that i wrote.
function formate(date) {
if (typeof date == "string")
date = new Date(date);
var day = (date.getDate() <= 9 ? "0" + date.getDate() : date.getDate());
var month = (date.getMonth() + 1 <= 9 ? "0" + (date.getMonth() + 1) : (date.getMonth() + 1));
var dateString = day + "/" + month + "/" + date.getFullYear() + " " + date.getHours() + ":" + date.getMinutes();
return dateString;
}
console.log(formate("2017-04-17 18:26:03"));
This will do the work:
var timestamp = Date.parse('2017-04-17 18:26:03'); // 1492467963000
var date = new Date(timestamp).toJSON(); // "2017-04-17T22:26:03.000Z"
var dateStr = date.slice(0, 10).split("-").reverse().join("/") // "17/04/2017"
.concat(' ')
.concat(date.slice(11, 16)); // "22:26"
console.log(dateStr)
"17/04/2017 22:26"

Jquery: How do i convert 1111-yyyy-mm-dd into 1111-mm/dd/yyyy

Using jquery/Javascript how can i convert a value with date 1111-2016-10-26 INTO 1111 - 10/26/2016 format ?
i tried below code but it did not helped.
var date = new Date('2010-10-11');
alert((date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear());
If you just want to convert without any date validations you can do it with string functions. Or if you want to use date functions, apply it only to that part of the string after splitting the string. Nothing fancy.
Use normal Date constructor (year,[month,[date...]]) when creating Date objects, passing non-standard formats is not recommended as the implementations are browser dependant.
var string = "1111-2016-10-26";
var a = string.split('-');
var number = a[0];
var date = a[2] + '/' + a[3] + '/' + a[1];
console.log(number + '-' + date);
var string = '1111-2010-10-11';
var a = string.split('-').map(Number);
var date = new Date(a[1], a[2] - 1, a[3]);
var dateString = ((date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear());
console.log(a[0]+ '-' + dateString);

Get last 36 hrs timestamp in javascript & compare it with php timestamp

I have a grid in which each row has a PHP format('Y-m-d H:i:s') date displayed.I wanted to apply a javascript filter which will show only those rows which has timestamp past 36hrs.
Whats the best way to first get past 36hrs timestamp & then compare that timestamp with displayed PHP timestamp using javascript.
Till now I tried using below code to get past 36 timestamp
var mydate=new Date();
mydate.setHours(mydate.getHours()-36);
dateInPhpFormat=mydate.getFullYear()+'-'+mydate.getMonth()+'- '+mydate.getDate()+"
"+mydate.getHours()+":"+mydate.getMinutes()+":"+mydate.getSeconds();
When I print dateInPhpFormat it shows wrong date.
Any help would be appreciated .
The only thing that could be wrong is that Javascript gives you the month, day, minues and seconds without leading zero. Also months are zero based, so you need to add 1 to the month.
For example month In JS: 3, in PHP(with 'm'): 03
You can add this leading zero yourself, like this;
var mydate=new Date();
mydate.setHours(mydate.getHours()-36);
var month = ('0' + (mydate.getMonth() + 1)).substr(-2);
var day = ('0' + mydate.getDate()).substr(-2);
var hour = ('0' + mydate.getHours()).substr(-2);
var minute = ('0' + mydate.getMinutes()).substr(-2);
var second = ('0' + mydate.getSeconds()).substr(-2);
dateInPhpFormat = mydate.getFullYear() + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
This will give you a date string which is identical to php date('Y-m-d H:i:s')
JavaScript Date objects use zero based months for some reason. Try adding 1 to the month.
dateInPhpFormat = mydate.getFullYear() + '-' + (mydate.getMonth() + 1 ) +'-'+mydate.getDate() + " " + mydate.getHours() + ":" + mydate.getMinutes() + ":" + mydate.getSeconds();

jQuery: add leading zeros to date string

I have a date string that is created by adding the following pieces:
var dateString = d + "/" + m + "/" + y;
The other variables are created previously in my code as being fetched from an internal web page (d = day, m = month, y = year).
This works fine so far.
How can I achieve that a leading zero is added to them if d and/or m consist of only digit ?
E.g. if d = 1 then it should become 01 and the same for m.
Many thanks in advance for any help with this, Tim.
I think it must be done manually.
var dateString = (d < 10? "0": "") + d + "/" + (m < 10? "0": "") + m + "/" + y;
There are some date formatting libraries/jQuery plugins around, but if this is all you need, they would be an overkill for that.
dateString.replace(/(^|\D)(\d)(?!\d)/g, '$10$2');
will add leading zeros to all lonely, single digits
Try following
var d_str = ("00" + d).slice(-2);
var m_str = ("00" + m).slice(-2);
var dateString_formatted = d_str + "/" + m_str + "/" + y;

Send Parameter DateTime in Javascript

I have a problem for sending parameters datetime type in javascript.
I have a function
function LoadHamuleFromDate(date) {
alert(date);
var day = date.toString().substr(0, 2);
var month = date.toString().substr(2, 2);
var year = date.toString().substr(4, 4);
var d = day + "." + month + "." + year;
alert(d);
}
When I send a date parameter to this function, my code crashed and I dont know why
document.getElementById("div_TarihButtonList").innerHTML += "<a class='small button'
' onclick='LoadHamuleFromDate(" + Number(result[i].tarih) + ")'>" + result[i].tarih + "</a></div>";
I can see results and have no problematic data, but when I click and send 10.10.2010
, I get this error: Uncaught SyntaxError: Unexpected identifier.
What can I do for this problem?
UPDATE:
more than likely the culprit is your Number() cast you are using.
onclick='LoadHamuleFromDate(" + Number(result[i].tarih) + ")'
Note: When using Number(), if the parameter is a Date object, the Number() function returns the number of milliseconds since midnight January 1, 1970 UTC.
Also, if you're not passing it a date, but actualy the string "10.10.2014" or similar, it will throw a NaN error as that is not a number or a date.
Remove the number cast and try again:
document.getElementById("div_TarihButtonList").innerHTML += "<a class='small button'
' onclick='LoadHamuleFromDate(" + result[i].tarih + ")'>" + result[i].tarih + "</a></div>";
SIDE NOTE:
i made a fiddle out of your javascript only, and it runs without errors. It does however alert the wrong result because your subst calls are wrong. IF your input is in the format DD.MM.YYYY, then it should look like this:
var day = date.toString().substr(0, 2);
var month = date.toString().substr(3, 2);
var year = date.toString().substr(6, 4);
As other posters have said, if you are getting the date format in multiple ways, your code needs to handle that as well. I'm just addressing what you said your date format was.
http://jsfiddle.net/CyBQJ/
You need to handle both the cases: 10102014 & 10.10.2014
Try this:
function LoadHamuleFromDate(date) {
var d, m, y;
d = date.toString().substr(0, 2); // day
if(!isNaN(date)){ // 10102014
m = date.toString().substr(2, 2);
y = date.toString().substr(4, 4);
} else { // 10.10.2014
m = date.toString().substr(3, 2);
y = date.toString().substr(6, 4);
}
alert(day + "." + month + "." + year)
}
==== EDIT =====
I have a better solution:
function LoadHamuleFromDate(date) {
var _date = date.toString().replace(/\./gi, ""), // conversion from 10.10.2014 to 10102014 format
day = _date.toString().substr(0, 2),
month = _date.toString().substr(2, 2),
year = _date.toString().substr(4, 4);
alert(date + " --> " + day + "." + month + "." + year);
//return _date;
}

Categories