print date like 'Y-m-d H:i:s"in javascript - javascript

Is there a built in way in javascript that formats a date object in a format like “Y-m-d H:i:s”?
I use
var since= new Date(xhr.getResponseHeader("Last-Modified"));
alert("modified:: " +since.getDate()+'.'+(since.getMonth()+1)+'. '+ since.getHours()+':'+since.getMinutes())
But that cuts off all leading zeros

You can try this:
function LeadingZero(s,max) {
var z = max-s.length+1;
z = z>1 ? Array(z).join('0') : '';
return (z + s);
}
alert("modified:: " +LeadingZero(since.getDate(),2)+'.'+LeadingZero(since.getMonth()+1,2)+'. '+ LeadingZero(since.getHours(),2));
But I recommend using Moment.js, a library for handling dates in JS. It has built in a formatter and can do a lot of other stuff.
In moment you can do it this way:
var d = moment(since);
alert(d.format('YYYY-MM-DD HH:mm:ss'));

Use this function:
function pad(number) {
if ( number < 10 ) {
return '0' + number;
}
return number;
}
pad(since.getDate())+'.'+pad(since.getMonth()+1)+'. '+ pad(since.getHours())+':'+pad(since.getMinutes())
For Y-m-d H:i:s format use following example:
pad(since.getFullYear()) + '-' + pad(since.getMonth()+1) + '-' + pad(since.getDate()) + ' ' + pad(since.getHours()) + ':' + pad(since.getMinutes()) + ':' + pad(since.getSeconds())

Related

issue between browsers with date pad function

I am trying to convert a date to a string and I am finding that my method works in firefox. But the same code comes up with a different and wrong time in both safari and chrome. I've put my code below. Can anyone see what might be wrong.
$(document).ready(function() {
var regLastSynchTime = new Date(item.date);
regLastSynchTimeStr = formattedTradingHourDateAndTime(regLastSynchTime);
});
var formattedTradingHourDateAndTime = function(date){
var d = pad(date.getDate());
var m = pad(date.getMonth() + 1);
var y = date.getFullYear();
var h = pad(date.getHours());
var mi = pad(date.getMinutes());
var ss = pad(date.getSeconds());
return d + '/'+ m + '/'+y + ' ' + h + ':' + mi + ':' + ss;
}
function pad(number) {
return (number < 10 ? '0' : '') + number;
}
Firefox (right)
Safari (Wrong)

SQL node.js Syntax error on what seems to be a valid query?

I'm running an update on a table to set a position. I've extracted the query and manually run it on my database and works fine but when passed through connection.query() it seems to think there's a syntax error in my node.js console.
function sendShipPosition(position) {
var input = '';
if (position.moving === true) {
var currentdate = new Date();
var datetime = currentdate.getFullYear() + "-"
+ (currentdate.getMonth()+1) + "-"
+ currentdate.getDate() + " "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();
var input = ', moving_datetime = ' + datetime;
}
connection.query('UPDATE ships SET x_axis = :x, y_axis = :y' + input + ' WHERE ship_id = :ship_id'), {
x: parseInt(position.x),
y: parseInt(position.y),
ship_id: 1
};
}
Here is the syntax error:
Here's the input data value of 'position' variable:
{ x: '-605', y: '-257', moving: 0 }
I hope I'm not being too much of a dunce and sorry for the low quality question.
Thanks
This function will generate SQL code which is missing quotes around the datetime variable, resulting in invalid SQL code.
function sendShipPosition(position) {
var input = '';
if (position.moving === true) {
var currentdate = new Date();
var datetime = currentdate.getFullYear() + "-"
+ (currentdate.getMonth()+1) + "-"
+ currentdate.getDate() + " "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();
# Here!
var input = ', moving_datetime = \'' + datetime + '\''
}
connection.query('UPDATE ships SET x_axis = :x, y_axis = :y' + input + ' WHERE ship_id = :ship_id'), {
x: parseInt(position.x),
y: parseInt(position.y),
ship_id: 1
};
}

Render a RealTime Clock after append in Jquery

I have tried many ways to make a live clock (with seconds) appear in a rendered table but it's not working propperly. The clock stays static, not showing second by second. I'm doing the following :
function myTable(){
var table = $('<table></table>');
table.append($('<tr>')
.append($('<td>')
.addClass('col2 data')
.attr('rowspan', '2')
.append($('<span>')
.attr('id', 'date_time')
)
)
)
$("#myDiv").html(table)
}
liveClock();
var liveClock = function () {
date = new Date;
//some logic here to generate the data I need the result above ( no problems here )
result = '' + d + '/' + month + '/' + year + ' ' + h + ':' + m + ':' + s;
var setDateTime = function() {
$("#date_time").html(result);
return false;
};
var everySec = setInterval(setDateTime, 1000);
}
Your problem is that you're never updating result, so each time your code fires SetDateTime, it renders the same date in the table. Move these lines:
date = new Date;
//some logic here to generate the data I need the result above ( no problems here )
result = '' + d + '/' + month + '/' + year + ' ' + h + ':' + m + ':' + s;
Into your setDateTime function.

changing gethours in javascript to 1-12

i'm trying to use the gethours() method in javascript but it keeps returning military time. can someone please help me out fixing it so that it displays clock time? (1-12). Thank you so much!
// Reroute from the conf.js script
var chat = $( '.chat-output' ),
message = function ( message, userId ) {
var dt = new Date(),
time = dt.getHours() + ":" + dt.getMinutes(); // + ":" + dt.getSeconds();
return $( '<div class="chat-message color-' + users[userId] + '">' +
'<div class="chat-id color-' + users[userId] + '"></div>' +
'<div class="chat-user-message">' + message + '</div>' +
'<div class="chat-time">' + time + '</div>' +
'</div>' );
},
addText = function ( text ) {
// log.innerHTML += text;
// log.scrollTop = log.scrollHeight;
console.log( text );
},
addRemoteText = function ( userId, text ) {
// addText( '[' + userId + ']: ' + text+'<br>' );
chat.append( message( text, userId ) );
chat.scrollTop( chat.get( 0 ).scrollHeight );
};
function ampm(date){
var dt= date || new Date,
h= dt.getHours(),
m= dt.getMinutes(),
s= dt.getSeconds(),
ampm;
if(h>12){
h-= 12;
ampm= (h%12)? ' PM': ' AM';
}
else ampm= (h%12)? ' AM': ' PM';
m= m<10? '0'+m: m;
s= s<10? '0'+s: s;
return [h, m, s].join(':')+ampm;
}
ampm()
/* returned value: (String)
11:52:55 PM
*/
Something like this?
var dt = new Date();
var hours = dt.getHours();
var ampm = hours > 11 ? 'PM' : 'AM';
if (hours > 12) {
hours -= 12;
} else if (hours === 0) {
hours = 12;
}
var time = hours + ":" + dt.getMinutes() + ' ' + ampm;
Fiddle
Here's another version of formatting a time in 12 hour format:
// Returns formatted time for given Date object, or
// current system time if d is falsey.
function getTime(d) {
d = d || new Date();
var hrs = d.getHours();
var pad = function(n){return (n<10?'0':'')+ +n};
return pad(hrs%12 || 12) + ':' + pad(d.getMinutes()) + ' ' + (hrs<12? 'AM':'PM');
}
console.log(getTime(new Date(2014,2,24, 0, 5))); // 12:05 AM
console.log(getTime(new Date(2014,2,24,10,25))); // 10:25 AM
console.log(getTime(new Date(2014,2,24,20,15))); // 08:15 PM
Note that 24hr time is preferred in many cases to avoid anomalies like 12:00 AM (which is really neither AM or PM) and 12:00 AM being before 01:00 AM.

Formatting date using jquery datepicker

I apologise if this is a really basic question but I am using the following jquery plugin:
http://jonathanleighton.com/projects/date-input
I want to change the date from YYYY-MM-DD to DD/MM/YYYY using his suggestion under customisations. I tried to do the following which I thought would work but it completely breaks it:
$.extend(DateInput.DEFAULT_OPTS, {
stringToDate: function(string) {
var matches;
if (matches = string.match(/^(\d{4,4})-(\d{2,2})-(\d{2,2})$/)) {
return new Date(matches[1], matches[2] - 1, matches[3]);
} else {
return null;
};
},
dateToString: function(date) {
var month = (date.getMonth() + 1).toString();
var dom = date.getDate().toString();
if (month.length == 1) month = "0" + month;
if (dom.length == 1) dom = "0" + dom;
return date.dom + "/" + month + "/" + getFullYear();
}
});
It's the following line where it all goes wrong:
return date.dom + "/" + month + "/" + getFullYear();
Could anyone offer a suggestion as to what I'm doing wrong?
You should try using the jQuery UI datepicker. Very easy to format the date
http://jqueryui.com/demos/datepicker/
i don't think you need the "date" in date.dom:
try replacing this:
return date.dom + "/" + month + "/" + getFullYear();
with this:
return dom + "/" + month + "/" + getFullYear();

Categories