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>
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 this code
$(document).ready(function () {
$("#btnsearch").click(function () {
var res = $("#txtSearch").val();
res = res.substring(0,9);
date = moment(res.val(), "DD/MM/YYYY HH:mm").format("DD-MM-YYYY HH:mm");
$("#calendar").fullCalendar('gotoDate', date);
}),
In frontend(Default.aspx):
<asp:Button Text="Search" id="btnsearch" runat="server" />
but when i charge the event page start and end parameters are set to today's date.:
public static List<CalendarEvent> getEvents(DateTime start, DateTime end)
{
List<CalendarEvent> events = new List<CalendarEvent>();
SqlConnection con = new SqlConnection(connectionString);
if (System.Web.HttpContext.Current.Session["Username"]!= null) {
String user= System.Web.HttpContext.Current.Session["Username"].ToString();
}
SqlCommand cmd = new SqlCommand("SELECT Id_xEvent,description, title, event_start, event_end, all_day,color,place FROM xEvent where event_start>=#start AND event_end<=#end", con);
// SqlCommand cmd = new SqlCommand("SELECT xDataConsRichiesta,xStatoAbbinamento,(convert(varchar,Id_DoTes) + ' ' + 'data doc: ' + convert(varchar,[DataDoc],103) + ' codice doc: ' + convert(varchar,[Cd_Do]) + ' tipo documento:' + convert(varchar,[TipoDocumento]) + ' codice cliente:' + convert(varchar,[Cd_CF])) as title ,(' codice cf dest:' + convert(varchar,[Cd_CFDest]) + ' codice cf sede:' + convert(varchar,isnull([Cd_CFSede],'')) + ' data consegna: ' + convert(varchar,[DataConsegna],103) + ' data trasporto ' + convert(varchar,isnull([TrasportoDataora],''),103) + ' volume: ' + convert(varchar,isnull([VolumeTotale],'')) + ' luogo scarico: ' + convert(varchar,isnull([Cd_DoLuogoScarico],'')) + ' tipo vettore:' + convert(varchar,isnull([xTipoVett],'')) + ' data cons richiesta: ' + convert(varchar,isnull([xDataConsRichiesta],''),103) + ' data consegna confermata:' + convert(varchar,isnull([xDataConsegnaConfermata],''),103)) as description FROM [ADB_isolkappa].[dbo].[DOTes] where xDataConsRichiesta BETWEEN #start and #end", con);
//SqlCommand cmd = new SqlCommand("SELECT event_id, description, title, event_start, event_end, all_day,color FROM Event e inner join dotes d on e.event_id=d.cd_xabbinamenti inner join xabbinamenti a on d.cd_xabbinamenti=a.cd_xabbinamenti where event_start>=#start AND event_end<=#end", con);
//SqlCommand cmd = new SqlCommand("SELECT (Cd_CF + ' ' + NumeroDocRif + ' ' + DataDocRif + ' ' + numerodoc + ' ' + xCaricoCompleto + ' ' + Cd_DoTrasporto + ' ' + xTipoVett + ' ' + Completo + ' ' + Data_Spedizione + ' ' + xDataConsegnaConfermata + ' ' + DataConsegna + ' ' + Cd_DoLuogoCarico + ' ' + Cd_DoLuogoScarico +' ' + xOKLogistica) as description, title, event_start, event_end, all_day, color FROM Event e inner join dotes d on e.event_id = d.cd_xabbinamenti inner join xabbinamenti a on d.cd_xabbinamenti = a.cd_xabbinamenti where event_start>= #start AND event_end<= #end");
cmd.Parameters.Add("#start", SqlDbType.DateTime).Value = start;
cmd.Parameters.Add("#end", SqlDbType.DateTime).Value = end;
//SqlCommand cmdIns = new SqlCommand();
//string stato="0";
using (con)
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
The getEvents function is called in JsonResponse.ashx
foreach (CalendarEvent cevent in EventDAO.getEvents(start, end))
{
tasksList.Add(new ImproperCalendarEvent {
id = cevent.id,
update:now the code
$("#btnsearch").click(function () {
var res = $("#txtSearch").val();
res = res.substring(0,10);
date = moment(res, "DD/MM/YYYY HH:mm").format("DD/MM/YYYY HH:mm");
$("#calendar").fullCalendar('gotoDate', date);
}),
with in default.aspx:
Search
it is positioned on the requested date but inverting the month with the day.For example if I search for an event on 03/09/2021 (dd / mm / yyyy) it positions itself on the week starting on 08/03/2021
fullCalendar 3 accepts momentJS objects directly. You don't need to pass it a formatted string.
If you do pass it a formatted string, it will try to parse it. But it doesn't know what format you intended, so if you pass something like 03/09/2021 it doesn't know if you intended that to be in dd/mm/yyyy or mm/dd/yyyy format - how could it tell? So it defaults to treating it as mm/dd/yyyy (probably because that's the default in the USA and a general standard default in JavaScript).
date = moment(res.val(), "DD/MM/YYYY HH:mm")
will work just fine.
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"));
I am trying to make a ajax load of a table. I have 2 buttons "Free Cars", "Reservations". When click "Free Cars" load all info from database and on click of tr it redirects to an url.
$('.cars_table').on('click', 'tr', function() {
var values = $(this).find('td').map(function() {
return $(this).text();
});
var startdate = $('input[name$="startdate"]').val();
var starttime = $('input[name$="starttime"]').val();
var enddate = $('input[name$="enddate"]').val();
var endtime = $('input[name$="endtime"]').val();
window.location.href = 'rental/create/' + values[0] + '~' + startdate + ' ' + starttime + '~' + enddate + ' ' + endtime + '';
});
Then on click of "Reservations" I change the class of tbody :
$('#cars_table').removeClass('cars_table').addClass('res_made');
But it doesn't perform the script which
$('.res_made').on('click', 'tr', function() {
var values = $(this).find('td').map(function() {
return $(this).text();
});
var startdate = $('input[name$="startdate"]').val();
var starttime = $('input[name$="starttime"]').val();
var enddate = $('input[name$="enddate"]').val();
var endtime = $('input[name$="endtime"]').val();
window.location.href = 'reservations/create/' + values[0] + '~' + startdate + ' ' + starttime + '~' + enddate + ' ' + endtime + '';
});
Instead it performs the first script and on click of reservations rows it goes to the .cars_table redirect url. With inspect element it shows that the class has changed but then it doesnt performs the script for that class. What is happening?
Event bindings happen on the DOM elements themselves. If you try to bind an event on all .res_made elements before there are any elements with this class, no events will be bound.
To solve your problem, you could bind your event once and check inside the handler which class is currently set.
You should dynamically bind the click events, because the class of the table can dynamically change. So to make it work in your case, you should change your javascript to the following:
$(document).on('click', '.cars_table tr', function() {
var values = $(this).find('td').map(function() {
return $(this).text();
});
var startdate = $('input[name$="startdate"]').val();
var starttime = $('input[name$="starttime"]').val();
var enddate = $('input[name$="enddate"]').val();
var endtime = $('input[name$="endtime"]').val();
window.location.href = 'rental/create/' + values[0] + '~' + startdate + ' ' + starttime + '~' + enddate + ' ' + endtime + '';
});
$(document).on('click', '.res_made tr', function() {
var values = $(this).find('td').map(function() {
return $(this).text();
});
var startdate = $('input[name$="startdate"]').val();
var starttime = $('input[name$="starttime"]').val();
var enddate = $('input[name$="enddate"]').val();
var endtime = $('input[name$="endtime"]').val();
window.location.href = 'reservations/create/' + values[0] + '~' + startdate + ' ' + starttime + '~' + enddate + ' ' + endtime + '';
});
See this FIDDLE for an example. Of course, as an alternative, you could also bind the event once and check for the class of the table in the event handler, like Martin Denk suggested.
I have a JavaScript code to get new time. But when i reload the page the time doesn't change instead it says 1/10/2014 10:57, how can i add a function for the time and date to detect and change
Below is the code I tried but its not working.
<script type="text/javascript">
(function () {
// using current UTC time from server as ref, display local time in div id="now"
var now = new Date();
now.setTime(1389322677492);
var nowstr = ""
+ (now.getMonth() + 1) + "/"
+ now.getDate() + "/"
+ ((now.getYear() < 1000) ? now.getYear() + 1900 : now.getYear()) + " "
+ now.getHours() + ":"
+ ((now.getMinutes() < 10) ? '0' + now.getMinutes() : now.getMinutes());
var el = document.getElementById("now");
el.appendChild(document.createTextNode(nowstr));
})();
</script>
Thanks for helping me.
Thats because you are explicitly setting it to 1389322677492 everytime. All you need to do is remove the line:
now.setTime(1389322677492);