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;
}
Related
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"
I try to write a function to convert date and time from string to date. Here's my code:
var date_one = '2015-08-12 14:15:00';
var date_two = '2015-08-13 15:00:00';
console.log(date_one); //2015-08-12 14:15:00
console.log(date_two); //2015-08-13 15:00:00
var timeStamp_date_one = new Date(date_one).getTime() ; //NAN?
console.log(typeof timeStamp_date_one);//number
var timeStamp_date_two = new Date(date_two).getTime() ;//NAN?
console.log(typeof timeStamp_date_two);//number
//since you are having both datetime in numer time
//you can compare then to any logical oparation ( >, < ,= ,!= ,== ,!== ,>= AND <=)
//to be able to work with this date and time agin you need to convert it to an object
var newTime = new Date(timeStamp_date_one) ;
console.log(typeof newTime) ;//object
// you can the use this following function to convert your date and time to any format you want
console.log(DateAndTimeFormat(newTime , 'time')) ;// NaN:NaN ???
console.log(DateAndTimeFormat(newTime , 'date_time')) ;// NaN/NaN/NaN NaN:NaN ???
function DateAndTimeFormat(dateAndTime, type) {
switch (type) {
case 'time':
return dateAndTime.getHours() + ':' + (dateAndTime.getMinutes() < 10 ? '0' : '') +
dateAndTime.getMinutes()
case 'date':
return dateAndTime.getMonth() + 1 + '/' + dateAndTime.getDate() + '/' +
dateAndTime.getFullYear()
case 'date_time':
return dateAndTime.getMonth() + 1 + '/' + dateAndTime.getDate() + '/' +
dateAndTime.getFullYear() + ' ' + dateAndTime.getHours() + ':' +
(dateAndTime.getMinutes() < 10 ? '0' : '') + dateAndTime.getMinutes()
}
}
Why in this case I talways take a "Not-a-Number" value ? I expect that Object could be transfered to Data object like in this code. Somebody can told my why and how can I repair that code? Thank's a lot
As specified by https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date, when working with years like you are doing, the format is not "YYYY-MM-DD HH:MM:SS" but "YYYY-MM-DDTHH:MM:SS" (Notice the 'T' instead of the space)
var date_one = '2015-08-12T14:15:00';
var date_two = '2015-08-13T15:00:00';
With these values, your code works.
This is relative to the ISO 8601 standard
I would recommend to parse and split into chunks the string representing the date first and then use new Date(year, month, day, hour, minutes, seconds, milliseconds); constructor to be 100% sure there are no any local date format issues.
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();
I want to convert UTC time value (e.g.1367214805) to date (in dd-mm-yyyy) format using javascript.
For e.g. in PHP if we use...
<?php Date("d-m-Y",'1367214805'); ?>
... we directly get the date in dd-mm-yyyy format.
Is there any such function in javascript?
- I tried Date() in various ways in javascript but every time it is printing the present date and time!!
Thanks
JavaScript uses millisecond epoch, so you need to multiply your number by 1000.
var t = 1367214805;
var d = new Date(t * 1000);
There are then .getUTCxxx methods to get the fields you want, and then you can just zero pad and concatenate to get the required string.
function epochToDate(t) {
function pad2(n) {
return n > 9 ? n : '0' + n;
}
var d = new Date(t * 1000);
var year = d.getUTCFullYear();
var month = d.getUTCMonth() + 1; // months start at zero
var day = d.getUTCDate();
return pad2(day) + '-' + pad2(month) + '-' + year;
}
Take a look at Moments.js, you should be able to get whatever format you want and easily.
console.log(new Date());
console.log(moment().format("D-M-YY"));
console.log(moment(1367214805 * 1000).format("DD-MM-YY"));
jsfiddle
You could use toISOString method and just ignore everything after the T e.g.
var isoDateStr = myDate.toISOString();
isoDateStr = isoDateStr.substring(0, isoDateStr.indexOf('T'));
This would give you standard UTC date format yyyy-mm-dd. If you need to specifically format the date as dd-mm-yyyy then you can take that result and switch the values i.e.
isoDateStr = isoDateStr.split('-').reverse().join('-');
You can try this:
myDate.toISOString().split('T')[0].split('-').reverse().join('-')
Why not use getUTCxxx() methods?
function formatUTC(time_UTC_in_milliseconds_since_epoch) {
/*
* author: WesternGun
*/
var time = new Date(time_UTC_in_milliseconds_since_epoch);
var formatted = time.getUTCFullYear() + "-"
+ (time.getUTCMonth() + 1).toString() + "-"
+ time.getUTCDate() + " "
+ time.getUTCHours() + ":"
+ time.getUTCMinutes() + ":"
+ time.getUTCSeconds();
return formatted;
}
Remember to add 1 to the month because the range of return value of getUTCMonth() is 0~11.
With your input, we have:
formatUTC(1367214805 * 1000); // return "2013-4-29 5:53:25"
To format the numbers into \d\d form, just create another function:
function normalizeNumber(input, toAdd) {
if (parseInt(input) < 10) {
return toAdd + input;
} else {
return input;
}
}
And use it like normalizeNumber((time.getUTCMonth() + 1).toString(), "0"), etc.
I need to output the current UTC datetime as a string with the following format:
YYYY/mm/dd hh:m:sec
How do I achieve that with Javascript?
You can build it manually:
var m = new Date();
var dateString = m.getUTCFullYear() +"/"+ (m.getUTCMonth()+1) +"/"+ m.getUTCDate() + " " + m.getUTCHours() + ":" + m.getUTCMinutes() + ":" + m.getUTCSeconds();
and to force two digits on the values that require it, you can use something like this:
("0000" + 5).slice(-2)
Which would look like this:
var m = new Date();
var dateString =
m.getUTCFullYear() + "/" +
("0" + (m.getUTCMonth()+1)).slice(-2) + "/" +
("0" + m.getUTCDate()).slice(-2) + " " +
("0" + m.getUTCHours()).slice(-2) + ":" +
("0" + m.getUTCMinutes()).slice(-2) + ":" +
("0" + m.getUTCSeconds()).slice(-2);
console.log(dateString);
No library, one line, properly padded
const str = (new Date()).toISOString().slice(0, 19).replace(/-/g, "/").replace("T", " ");
It uses the built-in function Date.toISOString(), chops off the ms, replaces the hyphens with slashes, and replaces the T with a space to go from say '2019-01-05T09:01:07.123' to '2019/01/05 09:01:07'.
Local time instead of UTC
const now = new Date();
const offsetMs = now.getTimezoneOffset() * 60 * 1000;
const dateLocal = new Date(now.getTime() - offsetMs);
const str = dateLocal.toISOString().slice(0, 19).replace(/-/g, "/").replace("T", " ");
With jQuery date format :
$.format.date(new Date(), 'yyyy/MM/dd HH:mm:ss');
https://github.com/phstc/jquery-dateFormat
Enjoy
I wrote a simple library for manipulating the JavaScript date object. You can try this:
var dateString = timeSolver.getString(new Date(), "YYYY/MM/DD HH:MM:SS.SSS")
Library here:
https://github.com/sean1093/timeSolver
Not tested, but something like this:
var now = new Date();
var str = now.getUTCFullYear().toString() + "/" +
(now.getUTCMonth() + 1).toString() +
"/" + now.getUTCDate() + " " + now.getUTCHours() +
":" + now.getUTCMinutes() + ":" + now.getUTCSeconds();
Of course, you'll need to pad the hours, minutes, and seconds to two digits or you'll sometimes get weird looking times like "2011/12/2 19:2:8."
Alternative to answer of #JosephMarikle
If you do not want to figth against timezone UTC etc:
var dateString =
("0" + date.getUTCDate()).slice(-2) + "/" +
("0" + (date.getUTCMonth()+1)).slice(-2) + "/" +
date.getUTCFullYear() + " " +
//return HH:MM:SS with localtime without surprises
date.toLocaleTimeString()
console.log(fechaHoraActualCadena);
Posting another script solution DateX (author)
for anyone interested
DateX does NOT wrap the original Date object, but instead offers an identical interface with additional methods to format, localise, parse, diff and validate dates easily. So one can just do new DateX(..) instead of new Date(..) or use the lib as date utilities or even as wrapper or replacement around Date class.
The date format used is identical to php date format.
c-like format is also supported (although not fully)
for the example posted (YYYY/mm/dd hh:m:sec) the format to use would be Y/m/d H:i:s eg
var formatted_date = new DateX().format('Y/m/d H:i:s');
or
var formatted_now_date_gmt = new DateX(DateX.UTC()).format('Y/m/d H:i:s');
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/UTC