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(/'/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"));
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>
It's my first time using a countdown in javascript so I have researched a little about this topic and I found some interesting links: "how to countdown to a date" and "https://www.sitepoint.com/build-javascript-countdown-timer-no-dependencies/", but my question is if I want to get data and time from the database, how can I do that? E.g.: I have a table Event with ID,Event,StartDate,StartTime and EndTime. How can I change from this: "var end = new Date('02/19/2012 10:1 AM');" from the first link or this: "Schedule the Clock Automatically" from the second to countdown time until event with the most recent time and date, and so on. Please keep in mind that I'm a total nooby so please bear with me. Sorry for any misspelling. Thank you!
Update:
This is the controller part: [HttpGet]
public JsonResult GetEvent(int Id)
{
BOL1.IMS2Entities db = new BOL1.IMS2Entities();
var ev = from e in db.tbl_Event
where e.ID == Id
select e;
//return Json(ev.FirstOrDefault(), JsonRequestBehavior.AllowGet);
return Json(Id, JsonRequestBehavior.AllowGet);
}
and this is the scripting part:
<script>
function GetEvent() {
debugger;
$.ajax({
type: "GET",
url: "Home/GetEvent",
data: { Id: ID },
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
debugger;
alert(result)
},
error: function (response) {
debugger;
alert('error');
}
});
}
var tbl_Event.StartDate = 'yyyy-MM-dd hh:hh:hh';
//var ServerDate_Time = '2017-02-17 10:45:00';
//console.log(CompareDateTime(ServerDate_Time));
console.log(CompareDateTime(tbl_Event.StartDate + tbl_Event.StartTime))
//function CompareDateTime (ServerDateTime){
function CompareDateTime (tbl_Event.StartDate + tbl_Event.StartTime){
var dateString = new Date();
var currentTime = new Date(parseInt(dateString));
var month = ('0' + (currentTime.getMonth() + 1)).slice(-2)
var day = ('0' + (currentTime.getDate())).slice(-2)
var year = currentTime.getFullYear();
var hours = ('0' + (currentTime.getHours())).slice(-2)
var min = ('0' + (currentTime.getMinutes())).slice(-2)
var sec = ('0' + (currentTime.getSeconds())).slice(-2)
var date = year + "-" + month + "-" + day + " " + hours + ":" + min + ":" + sec;
if(ServerDateTime == date){
return true;
}else {
return false;
}
}
}
</script>
assuming your datetime you are getting int tbl_Event.StartDate + tbl_Event.StartTime = 2017-02-17 10:45:00
this will go for your..
var ServerDate_Time = '2017-02-17 10:45:00';
console.log(CompareDateTime(ServerDate_Time));
function CompareDateTime (ServerDateTime){
var dateString = new Date();
var currentTime = new Date(parseInt(dateString));
var month = ('0' + (currentTime.getMonth() + 1)).slice(-2)
var day = ('0' + (currentTime.getDate())).slice(-2)
var year = currentTime.getFullYear();
var hours = ('0' + (currentTime.getHours())).slice(-2)
var min = ('0' + (currentTime.getMinutes())).slice(-2)
var sec = ('0' + (currentTime.getSeconds())).slice(-2)
var date = year + "-" + month + "-" + day + " " + hours + ":" + min + ":" + sec;
if(ServerDateTime == date){
return true;
}else {
return false;
}
}
Hope this helps....
Edit after your Edit ....
Updated code...
For Controller --
[HttpGet]
public JsonResult GetEvent(int id)
{
using (IMS2Entities ObjEntities = new IMS2Entities())
{
var ev = from e in ObjEntities.tblEvents
where e.id == id
select e;
return Json(ev.ToList(), JsonRequestBehavior.AllowGet);
}
}
JavaScript code for this
<script>
$(function () {
GetEvent(); // this will call GetEvent function once your DOM is ready, you can call this function on button click or anywhere as per your need.
function GetEvent() {
$.ajax({
type: "GET",
url: "/Home/GetEvent",
data: { Id: '1' }, // '1' is id for my sql database record which is passing to controller to bring back record from server.
success: function (result) {
// result will be collection of list return form server, since you are using id criteria it will always have only 1 record unless you have id as foreign key or something not primary/unique.
// I'm using only first instance of result for demo purpose, you can modify this as per your need.
alert(CompareDateTime(result[0].StartDateTime.substr(6))); // this will alert your true or false, as per I guess this will always return false, as your current date time will never match sql datetime. Still for your requirement.
},
error: function (response) {
alert(response);
}
});
}
function CompareDateTime (ServerDateTimeFormat){
// Convert ServerDateTimeFormat for Comparision
var ServerdateString = ServerDateTimeFormat;
var ServerCurrentTime = new Date(parseInt(ServerdateString));
var Servermonth = ('0' + (ServerCurrentTime.getMonth() + 1)).slice(-2)
var Serverday = ('0' + (ServerCurrentTime.getDate())).slice(-2)
var Serveryear = ServerCurrentTime.getFullYear();
var Serverhours = ('0' + (ServerCurrentTime.getHours())).slice(-2)
var Servermin = ('0' + (ServerCurrentTime.getMinutes())).slice(-2)
var Serversec = ('0' + (ServerCurrentTime.getSeconds())).slice(-2)
var Serverdate = Serveryear + "-" + Servermonth + "-" + Serverday + " " + Serverhours + ":" + Servermin + ":" + Serversec;
// Current Date Time for Comparision
var currentTime = new Date();
var month = ('0' + (currentTime.getMonth() + 1)).slice(-2)
var day = ('0' + (currentTime.getDate())).slice(-2)
var year = currentTime.getFullYear();
var hours = ('0' + (currentTime.getHours())).slice(-2)
var min = ('0' + (currentTime.getMinutes())).slice(-2)
var sec = ('0' + (currentTime.getSeconds())).slice(-2)
var date = year + "-" + month + "-" + day + " " + hours + ":" + min + ":" + sec;
if (date == Serverdate) {
return true;
}else {
return false;
}
}
});
</script>
Please make sure you put reference for JQuery before ... tag.
This is fully working example.. :)
I need a help.
I would like to see the last 24 hours in the timeline Chart. This is the formatted datetime DD/MM/YYYY HH:MM:SS.
This is the data source: https://docs.google.com/spreadsheets/d/1H602ZpDfwl044qjDyIDfscOWoaSqLzjsvb3TuZXEK6c/edit#gid=0
I'm getting en error: Uncaught SyntaxError: Unexpected token ILLEGAL
Does anyone have any idea to solve this?
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization',
'version':'1','packages':['timeline']}]}"></script>
<script type="text/javascript">
google.setOnLoadCallback(drawChart);
function drawChart() {
var dataTable = new google.visualization.DataTable();
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1H602ZpDfwl044qjDyIDfscOWoaSqLzjsvb3TuZXEK6c/edit#gid=0');
var nowone = getNowDate();
query.setQuery("select A,B,C where B >= datetime '"+nowone+"' ");
query.send(handleQueryResponse);
}
function getNowDate(){
var d=new Date();
d.setDate(d.getDate() - 1);
var year = d.getFullYear();
var month = d.getMonth() + 1;
var day = d.getDate();
var hour = d.getHours();
var minute = d.getMinutes();
var second = d.getSeconds();
var microsecond = d.getDate();
if (month.toString().length == 1) {
month = '0' + month;
}
if (day.toString().length == 1) {
day = '0' + day;
}
if (hour.toString().length == 1) {
hour = '0' + hour;
}
if (minute.toString().length == 1) {
minute = '0' + minute;
}
if (second.toString().length == 1) {
second = '0' + second;
}
//while(microsecond.toString().length < 3) {
// microsecond = '0' + microsecond;
//}
var dateString = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second';
return dateString;
}
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var options = {
timeline: { singleColor: '#8d8' },
};
var container = document.getElementById('example5.2');
var chart = new google.visualization.Timeline(container);
chart.draw(data, options);
setTimeout(drawChart, 5000);
}
</script>
</head>
<body>
<div id="example5.2" style="height: 500px;"></div>
</body>
</html>
This is purely a JS issue. You have an extra quote in JS that doesn't belong. When you set your time, it should be:
var dateString = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
Instead of
var dateString = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second';
If you remove the extraneous quote, your error will go away.
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.