How to modify date formate in ajax js code? - javascript

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>'

Related

date.toLocaleTimeString is not a function

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/>");
}

Load JS function inside a div

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>

Change the format of a date to dd/MM/yyyy

Anybody know how to adjust the current JS code and make it so the [ItemDate] shows the date in dd/MM/yyyy format instead of defaulted: MM/dd/yyyy HH:mm:ss
The code is copied from a website which converts XML into a readable HMTL format... trouble is only the date.format where I find it hard to implement the change.
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
SPClientTemplates.TemplateManager.RegisterTemplateOverrides({
Templates: {
Fields: {
'ItemsOverview': {
'View': repeatingSectionViewTemplate
}
}
}
});
function repeatingSectionViewTemplate(ctx) {
var xml = ctx.CurrentItem["ItemsOverview"];
var decodedxml = xml.DecodeXMLNotation();
var htm = "";
xmlDoc = $.parseXML( decodedxml );
$xml = $( xmlDoc );
$xml.find("Item").each(function() {
htm = htm + "<tr><td width='50px'>" + $(this).find("ItemNumber").text() + "</td><td width='140px'>" + $(this).find("ItemDescription").text() + "</td><td width='70px'>" + $(this).find("ItemStatus").text() + "</td><td>" + $(this).find("ItemDate").text()
+"</td><td>" + $(this).find("CollectedByUser").text() +"</td></tr>";
});
return "<table border='1px' width='550px' style='border-collapse:collapse;'><tr><th align='left' width='50px'>Item</th><th align='left' width='180px'>Description</th><th align='left' width='70px'>Status</th><th align='left' width='70px'>Date</th><th align='left' width='170px'>Collected By</th></tr>" + htm +"</table>";
};
//Replaces html notation to their equivalent xml escape characters.
String.prototype.DecodeXMLNotation = function () {
var output = this;
if ($.trim(output) != "") {
output = output.replace(/&apos;/g, "'").replace(/"/g, '"').replace(/>/g, '>').replace(/</g, '<').replace(/&/g, '&');
}
else {
output = "";
}
return output;
};
</script>
You'd have to create a function that reformats the date for you.
function formatDate(dateStr) {
const d = new Date(dateStr);
return d.getDate().toString().padStart(2, '0') + '/' + d.getMonth() + 1 + '/' + d.getFullYear() + ' ' + d.getHours() + ':' + d.getMinutes().toString().padStart(2, '0');
}
And instead of $(this).find("ItemDate").text() you'd use formatDate($(this).find("ItemDate").text())
Best way to do this is Moment.js plugin.
moment().format('DD/MM/YYYY);
var newDate = new Date();
console.log(newDate);
var formattedDate = moment().format('DD/MM/YYYY');
console.log(formattedDate);
<script src="https://momentjs.com/downloads/moment.js"></script>
Either use the Moment.js plugin:
Install using:
npm install moment --save
Then use
var moment = require('moment');
let formatted = moment().format('DD/MM/YYYY');
in your file.
Or if you are doing it inline in html then use:
<script src="moment.js"></script>
<script>
let formatted = moment().format('DD/MM/YYYY');
</script>
OR
You can use the following function that converts to the same format:
parseDate = (d) => {
let date = new Date(d);
var mm = date.getMonth() + 1; // getMonth() is zero-based
var dd = date.getDate();
let newdate = [(dd>9 ? '' : '0') + dd + '/',
(mm>9 ? '' : '0') + mm+ '/',
date.getFullYear(),
].join('');
return newd + ' at ' + date.getUTCHours() + ':' + date.getUTCMinutes() + ':' + date.getUTCSeconds();
}
Hope this helps.
I think that "dd/MM/yyyy" is a french format:
var date = new Date('12/17/2018 03:24:00');
console.log(date.toLocaleDateString("fr-FR"));

How to display Json date string as DD/MM/YYYY in a table [duplicate]

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.

lastModified date format to UK standard

I am trying to display when a webpage was last loaded and need to alter the format of the date from 05/18/2015 11:47:39 to 18/05/2015 thanks I am currently using the following :
<script language="Javascript">
document.write("last refreshed: " + document.lastModified +"");
</SCRIPT>
You could write a function that formats a date to your required format:
function formatAsUKDate(date) {
var day = padWithZero(date.getDate(), 2);
var month = padWithZero(date.getMonth()+1, 2);
var year = date.getFullYear();
return day + '/' + month + '/' + year;
}
function padWithZero(str, minLength) {
str = String(str);
while (str.length < minLength) {
str = '0' + str;
}
return str;
}
And in your HTML:
<script language="Javascript">
document.write("last refreshed: " + formatAsUKDate(document.lastModified) +"");
</SCRIPT>
You can use the Date object, as:
var d = new Date("05/18/2015 11:47:39");
Then retrieve the data as you want it.
Such as d.getMonth()+1;
Then finally concatenate as you wish.

Categories

Resources