lastModified date format to UK standard - javascript

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.

Related

How to modify date formate in ajax js code?

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

knockout data-bind date NaN/NaN/NaN

I just tried to make a span with formatted date under foreach using knockout
I have this script
Date.prototype.toFormattedDate = function () {
var dd = this.getDate();
if (dd < 10) dd = '0' + dd;
var mm = this.getMonth() + 1;
if (mm < 10) mm = '0' + mm;
var yyyy = this.getFullYear();
/* change format here */
return String(dd + "/" + mm + "/" + yyyy);
};
and in html i try this
<span class="form-control" data-bind="text: new Date(my_date).toFormattedDate() " />
my_date is a string date "2020-09-13T00:00:00"
but it always shows NaN/NaN/NaN
i tried to use moment.js but it gave me "Invalid date"
Demo:
Date.prototype.toFormattedDate = function() {
var dd = this.getDate();
if (dd < 10) dd = '0' + dd;
var mm = this.getMonth() + 1;
if (mm < 10) mm = '0' + mm;
var yyyy = this.getFullYear();
/* change format here */
return String(dd + "/" + mm + "/" + yyyy);
};
const formatted = new Date("2020-09-13T00:00:00").toFormattedDate();
console.log(formatted)
It's happening because my_date is an observable. new Date(my_date) will try to convert the observable to a date and it fails. So, get the value in the observable by using my_date() and use it in the new Date() constructor
Date.prototype.toFormattedDate = function(){var a=this.getDate();if(a<10){a="0"+a}var b=this.getMonth()+1;if(b<10){b="0"+b}var c=this.getFullYear();return String(a+"/"+b+"/"+c)};
ko.applyBindings({ my_date: ko.observable('2020-09-13T00:00:00') })
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<span class="form-control" data-bind="text: new Date(my_date()).toFormattedDate() " />
Another option is to create a custom binding for your date format. You could move all the date format code to the custom binding directly if you don't want to pollute Date.prototype
function customDateHandler(element, valueAccessor) {
var value = ko.unwrap(valueAccessor());
element.textContent = new Date(value).toFormattedDate()
}
ko.bindingHandlers.customDateFormat = {
init: customDateHandler,
update: customDateHandler
};
And use the binding in your span:
<span class="form-control" data-bind="customDateFormat: my_date" />
Here's a snippet:
function customDateHandler(element, valueAccessor) {
var value = ko.unwrap(valueAccessor());
element.textContent = new Date(value).toFormattedDate()
}
ko.bindingHandlers.customDateFormat = {
init: customDateHandler,
update: customDateHandler
};
Date.prototype.toFormattedDate = function(){var a=this.getDate();if(a<10){a="0"+a}var b=this.getMonth()+1;if(b<10){b="0"+b}var c=this.getFullYear();return String(a+"/"+b+"/"+c)};
ko.applyBindings({ my_date: ko.observable('2020-09-13') })
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<span class="form-control" data-bind="customDateFormat: my_date" />

How can i remove minutes or disable minutes from my time zone using moment.js?

I am using moment.js in date range picker I want to hide or disable my minutes hand. What can i do, here is my code which I tried :
function cb(start, end) {
$('#reportrange span').html(start.format('YYYY-MM-DD hh') + ' - ' + end.format('YYYY-MM-DD hh'));
$('#hidreportrange').val(start.format('YYYY-MM-DD hh'));
var selecteddate = start.format('YYYY-MM-DD hh');
var con = new Date(selecteddate);
var datestring = con.toString();
$("#spnseldate").html(datestring.split(" ")[2] + " " + datestring.split(" ")[1] + " " + datestring.split(" ")[3]);
// $("#spncurrentDate").html(DataBaseManager.DateTimeFormat(start.format('YYYY-MM-DD')));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script>
function abc(start,end){
console.log(moment(start).format('MM-DD-YYYY HH:mm:ss'),moment(end).format('DD-MM-YYYY HH:mm:ss'));
}
abc(new Date(),new Date());
</script>
you can use like that if you are using moment.js then you have to pass your date
in that function.

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

javascript change textbox value onchange

I have a StartDate and an ExpiryDate textbox. Both take values in the forms of 10/12/2013.
What I would like to be able to do is, when you change the StartDate textbox (whether from empty or just updating the date) the ExpiryDate textbox needs to add 1 year onto the date.
Example:
If StartDate = 10/12/2013 then ExpiryDate will automatically change to 10/12/2014.
How to do that with JS?
function MyFunc() {
MyTextBox = document.getElementById("<%= TextBox1.ClientID %>");
MyTextBox2 = document.getElementById("<%= TextBox2.ClientID %>");
var date = new Date(MyTextBox.value);
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear() + 1;
MyTextBox2.value = day + "/" + month + "/" + year;
}
Try this, call the setExpiryDate() function whenever you need to set the expiration date.
function setExpiryDate() {
var txtStartDate = document.getElementById("ctrl1");
var txtExpiryDate = document.getElementById("ctrl2");
var dt = new Date(txtStartDate.value);
if (!isNaN(dt)) {
dt = dt.setYear(dt.getYear() + 1);
txtExpiryDate.value = padStr(temp.getDate()) + '/' + padStr(temp.getMonth() + 1) + '/' + temp.getFullYear().toString();
}
}
function padStr(i) {
return (i < 10) ? "0" + i : "" + i;
}
How about this:
function updateInput(value){
document.getElementsById('Yourelement').Value = value;
}
Other than that, all you need is some date parsing/string manipulation to find the correct year.

Categories

Resources