Am trying to print the date from script.js coming from mongodb but am getting the below error
Uncaught TypeError: date.toLocaleTimeString is not a function
function db_old_msgs(old_msg) {
$('.chat-messages').append('<span class="msg"><b>' + old_msg.nick + ': </b>' + old_msg.msg +" "+FormatTime(old_msg.created) + "</span><br/>");
}
function FormatTime(time, prefix = "") {
var date = Date.parse(time);
return ((typeof time != "undefined") ? prefix + date.toLocaleTimeString() : "");
}
I tried the above without the function FormatTime like "+ old_msg.created.toLocaleTimeString() +" but I get the same error.
The time format that is received from db is 2021-12-16T13:22:01.600+00:00.
Dates are being displayed correctly which are coming from server.js
socket.broadcast.emit('msg', {from: users[socket.id],message: message, time:newMsg.created.toLocaleTimeString()})
Many thanks
The date was coming as string from the server so I had to convert it to date and then pass the function toLocaleTimeString()
function db_old_msgs(old_msg) {
var dbtime=new Date(old_msg.created);
var formattedDate = dbtime.toLocaleTimeString();
$('.chat-messages').append('<span class="msg"><b>' + old_msg.nick + ': </b>' + old_msg.msg +" "+formattedDate + "</span><br/>");
}
Related
I have a js ajax code:
success:function(res){
var _html='';
var json_data=$.parseJSON(res.posts);
$.each(json_data,function (index,data) {
_html+='<span class='time'>'+data.fields.time+'</span>';
});
$(".post-wrapper").append(_html);
}
The issue is the time format is like:
2021-08-05T22:10:55.255Z
How to modify this date formate to something like:
2021-08-05 22:10
You should be able to just format it within that success function :
var _html='';
var json_data=$.parseJSON(res.posts);
$.each(json_data,function (index,data) {
let datetime = data.fields.time;
let formatted_date = datetime.getFullYear() + "-" +
(datetime.getMonth() + 1) + "-" + datetime.getDate() + " "
+ datetime.getHours() + ":" + datetime.getMinutes();
_html+='<span class='time'>'+ formatted_date +'</span>';
});
Check out the docs for Moment.js, this should do the trick for you: http://momentjs.com/docs/#/parsing/string+format.
example:
<span class='time'>'+moment(data.fields.time).format("YYYY-MM-D HH:mm")+'</span>'
I have a simple span and I want to show full date from Javascript inside this span. I'm not getting how to do it.
HTML (The date would be in place of the "..."):
<h3>Data Atual: </h3><span id="date" onload="newDate()">...</span>
Javascript:
function newDate() {
var dateBox = document.getElementById('date');
dateBox.innerHTML = '';
var date = new Date();
var newDate = date.getDay + ', ' + date.getDate + ' de ' + date.getMonth + ', ' + date.getFullYear + '.';
dateBox.innerHTML += newDate;
}
Thanks in advance
The load event doesn't fire on static HTML elements, only elements that load their data asynchronously from an external URL.
Put the call in the body's onload event.
<body onload="newDate()">
you can use this code to show the complete day in your span text:
document.getElementById("date").innerHTML = createNewDate();
function createNewDate() {
const date = new Date();
const newDate = date.getDay + ', ' + date.getDate + ' de ' + date.getMonth + ', ' + date.getFullYear + '.';
return newDate;
}
do not need to load it on start. Actually you are using get dates wrongly. This following code will solve it your problem. Put it before </body>
<script>
var date = new Date();
var newDate = date.getDay() + ', ' + date.getDate() + ' de ' + date.getMonth() + ', ' + date.getFullYear() + '.';
document.getElementById("date").innerHTML = newDate;
</script>
This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 6 years ago.
I'm trying to format some json dates in a table to a more readable format. The string returned from the json looks like this "2015-06-29T10:00:00.000Z".
The time is not important, I just want to show the date as dd/mm/yyyy.
I have tried using new date(detestring) but i might have got this wrong, as its not working. Here is the full code.
$(document).ready( function() {
$.getJSON( 'opp.php', function(data) {
$.each(data.opportunities, function() {
$("table#outtodaytomorrow").append("<tr><td>" + this.number + "</td><td>" + new Date(this.starts_at) + "</td></tr>");
});
});
});
Any help much appreciated.
You have to create your own function which achieve your target.
function formatDate(stringDate){
var date=new Date(stringDate);
return date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear();
}
Your code:
$("table#outtodaytomorrow").append("<tr><td>" + this.number + "</td><td>" + formatDate(this.starts_at) + "</td></tr>");
You could use MomentJs to parse the first input and then format it to your desired format. Something like :
$(document).ready( function() {
$.getJSON( 'opp.php', function(data) {
$.each(data.opportunities, function() {
$("table#outtodaytomorrow").append("<tr><td>" + this.number + "</td><td>" + moment(this.starts_at).format("DD/MM/YYYY") + "</td></tr>");
});
});
});
See Format date to MM/dd/yyyy in javascript
First, parse it to a date with
var date = new Date(this.starts_at);
Second, print your date as desired
var dateStr = (date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear())
You will get "6/29/2015"
For your specific instance, it would be something like
$(document).ready( function() {
$.getJSON( 'opp.php', function(data) {
$.each(data.opportunities, function() {
var date = new Date(this.starts_at);
var dateStr = (date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear())
$("table#outtodaytomorrow").append("<tr><td>" + this.number + "</td><td>" + dateStr + "</td></tr>");
});
});
});
Breaking up the component into different pieces of memory such as "date" and "dateStr" makes it easier to read and understand.
In the following snippet of my code, I post to a link, from which it allows me to change the title, but will not call the function info() with the argument supplied, nor will it log in the console, please help with this code, thanks. Also, please note all the variables are defined and this code works 100% besides this, and it won't work with $.get rather than $.post either.
function info(text, state) {
$("<h4>"+text+"</h4>").appendTo("body");
if (state != "run") {
$("h2").text(text).fadeIn("slow").delay(30000).fadeOut();
}
$.post(buy, function(r) {
diff = event.timeStamp - last;
$(document).prop('title', 'Purchased '+info['itemName']+'!');
info('Purchased '+info['itemName']+' for '+info['expectedPrice']+' in '+diff+' milliseconds!');
console.log('Purchased '+info['itemName']+' for '+info['expectedPrice']+' in '+diff+' milliseconds!');
})
--EDIT--
If I put console.log above info, the code works excluding the info() function, so the problem is possibly there
Try (this pattern)
// var last = $.now();
function info(text, state) {
$("<h4>" + text + "</h4>").appendTo("body");
if (state != "run") {
$("h2").text(text).fadeIn("slow").delay(30000).fadeOut();
}
// missing closing `{` at OP
};
$.post(buy, function (_info) {
// `_info` : return json object
// `info` : function declaration name
// diff = $.now() - last;
$(document).prop('title', 'Purchased ' + _info['itemName'] + '!');
info('Purchased '
+ _info['itemName'] + ' for '
+ _info['expectedPrice'] + ' in '
+ diff + ' milliseconds!'
, "run");
console.log('Purchased '
+ _info['itemName'] + ' for '
+ _info['expectedPrice'] + ' in '
+ diff + ' milliseconds!');
});
jsfiddle http://jsfiddle.net/guest271314/7vxb7336/
I'm developing an Android App using Phone Gap, and I have problems getting the current time in the javascript file.
I've tried using the standard Date() call and I get nothing.
function getCurrentTime(){
//get current time
var currentTime = new Date();
var timestamp = JSON.stringify(currentTime);
console.log('current time: ', timestamp);
}
prints "current time: "
The only other reference I found on phonegap documentation was this:
var onSuccess = function(position) {
alert('Latitude: ' + position.coords.latitude + '\n' +
'Longitude: ' + position.coords.longitude + '\n' +
**********'Timestamp: ' + new Date(position.timestamp) + '\n');
};
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
navigator.geolocation.getCurrentPosition(onSuccess, onError);
I tried using it but it still prints nothing. Any idea?
var success = function(p) {
bkme.flags.gettingLocation = false;
bkme.data.geolocation = {
'lat' : p.coords.latitude,
'lon' : p.coords.longitude,
'accuracy' : p.coords.accuracy,
'valid' : true
};
console.log('time:', new Date(p.timestamp));
};
var fail = function(error) { };
navigator.geolocation.getCurrentPosition(success, fail);
This is what I use for my app and it works fine
var date = new Date();
var hour = date.getHours();
var min = date.getMinutes();
var seconds = date.getSeconds();
Hope it helps
Have you tried skipping the JSON.stringify call?