Replace ISO-Date with normal Date in HTML Document via Widget - javascript

my problem is the following . Im using Duda widget Builder to build my own Widgets. In one application there is a Date and by default its depicted as ISO .
Now converting that isnt too hard, I tried the following :
if (document.getElementById("date") !== null) {
let date = document.getElementById("date").toString();
let dater = date.substring(0, 10);
document.getElementById("date").innerHTML.replace(date, dater);
console.log('Test');
}
<div class="Wrapper shadow">
<h3 class="date" id="date">2020-02-20T14:39:40Z</h3>
</div>
Now it doesnt throw any errors and it console.logs the "Test". But the date stays in ISO.
The widget works with jQuery I believe it has something to do with that.
The widget interface where you write down the javascript is encapsulated by this: function(element,data,api){ 'my js code from above'}
Please help.

The issue is because you never update the content of the element after working with the content. Also note that you don't need to use replace(). Try this:
let el = document.getElementById("date");
if (el) {
el.textContent = el.textContent.substring(0, 10);
}
<div class="Wrapper shadow">
<h3 class="date" id="date">2020-02-20T14:39:40Z</h3>
</div>
That being said, you're just getting the first 10 characters of the date string, which is not infallible. If the locale changes your code will break. To fix this you can create a Date object from the string and output the format you require explicitly:
let el = document.getElementById("date");
if (el) {
let date = new Date(el.textContent);
let year = date.getFullYear();
let month = ("00" + (date.getMonth() + 1)).slice(-2);
let day = ("00" + date.getDate()).slice(-2);
el.textContent = `${year}-${month}-${day}`;
}
<div class="Wrapper shadow">
<h3 class="date" id="date">2020-02-20T14:39:40Z</h3>
</div>

You can also use Moment.js for format the date you need.
const el = document.querySelector('#date');
const myDateFormat = 'YYYY-MM-DD';
const date = el.textContent;
const newDate = moment(date, myDateFormat).format(myDateFormat);
el.textContent = newDate;
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<div class="Wrapper shadow">
<h3 class="date" id="date">2020-02-20T14:39:40Z</h3>
</div>
Hope to help you and others ^^.

Related

How to Show HTML Text into Javascript

I tried to show some text into javascript but unable to do
First of all, here is the code
$('.example').each(function() {
var $t = $(this),
$w = $t.find('.widget.Text');
if ($w != undefined) {
months = $(this).text().replace($w, 'months');
days = $(this).text().replace($w, 'days');
months != false && $t.find('#example-done').text(months);
days != false ? days = Number(days) : days = 7;
}
});
// up to so...............on
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="example">
<div class="widget Text">
months=(Accept) days=(20)
</div>
</div>
Here in the above code months and days data shows I tried to implement this data in javascript
months=(Accept) its value should be Accept in Js
days=(20) its value should be 20 Accept in Js
I tried the above method but not working
is there any method available to insert the above HTML format data in my Javascript
I think .split() function will resolve this problem please provide any guide (like we have to split both data with help of js and Text Trim)
Any help is highly appreciated
I just want to show months and days values into my javascript code, Please provide any code to fix this issue. I tried hard but I am unable to fix it. Like months=(Accept) and days=(20), Now how to show that value (20 and accept) into javascript? Please leave other code which I provide above Just guide me on how to show this HTML format data into js
Use .text() to get the contents of the DIV. Then you can use a regular expression to match the contents and extract the values.
$('.example').each(function() {
var $t = $(this),
$w = $t.find('.widget.Text').text();
if ($w) {
var match = $w.match(/months=\(([^)]*)\)\s+days=\((\d+)\)/);
if (match) {
var months = match[1];
var days = Number(match[2]);
console.log(`Months = ${months}, Days = ${days}`);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="example">
<div class="widget Text">
months=(Accept) days=(20)
</div>
</div>
See Reference - What does this regex mean? for explanations of the regular expression details.
Change
months = $(this).text().replace($w, 'months');
days = $(this).text().replace($w, 'days');
months != false && $t.find('#example-done').text(months);
days != false ? days = Number(days) : days = 7;
to
let a = $t.text().match(/months=\(([^(]*)\)\s+days=\(([^(]*)\)/);
months = a[1]; days = a[2];
days = days === '' ? 7 : +days;

Get date from bootstrap-datepicker and print separately

I am using Bootstrap Date picker. I want to get date value(20-Sep-19) and print it in three different div's(so as i can style them differently).
<div class="input-group date">
<input type="hidden" id="date-input" value="20-Sep-19" class="form-control">
<div id="div1">20 </div>
<div id="div2">Sep'19</div>
<div id="div3">Wednesday</div>
</div>
$(function(){
$('.input-group.date').datepicker({
format: 'dd-M-yy',
todayHighlight: true,
autoclose: true});
});
I have tried some jquery but doesn't work.
$(document).on("change", "#date-input", function () {
var date = new Date($('#date-input').val());
day = date.getDate();
month = date.getMonth() + 1;
year = date.getFullYear();
alert([day, month, year].join('/'));
});
Anyone know how this can be achieved. Thanks in Advance.
Check out this fiddle for a quick implementation.
Your Javascript will need to parse the data sent back from the dateChange event of the datepicker element
picker.on("changeDate", function(e) {
div1.text(e.date.getDate());
var month = getMonthName(e.date.getMonth());
var year = ("" + e.date.getYear()).substr(1, 3);
div2.text(month + " '" + year);
div3.text(getDayOfWeek(e.date.getDay()));
});
The getMonthName and getDayOfWeek functions simply take in an integer and return the corresponding month/day.
From the sounds of things, you're relatively new to Javascript. I would highly recommend that you fully understand how to utilize Javascript and jQuery.
Please see the following resources for more information:
* JS Date and utilities
* jQuery .text()
* Bootstrap-datepicker changeDate documentation

Show string result from function in a label using AngularJs

What is the best way to call function that will return string and show that string in a label when using angularJs?
I have three drop downs, and when I select values in all of them I want to show a label.
Content of a label is calculated in one function so on that moment (when all 3 drop downs have some values selected) I need to call function that will return value for label as well.
All that hiding/showing label logic I have put in html like this:
<div class="col-md-2"
ng-show="newTestSessionCtrl.formData.sessionTime && newTestSessionCtrl.formData.timeZone && newTestSessionCtrl.formData.sessionCloseInterval">
<lable>Your local time</lable>
<div ng-value="convertSelectedTimeZoneToClients()"></div>
</div>
This is convertSelectedTimeZoneToClients() function code:
convertSelectedTimeZoneToClients() {
let timeZoneInfo = {
usersTimeZone: this.$rootScope.mtz.tz.guess(),
utcOffset: this.formData.timeZone.offset,
selectedDateTime: this.toJSONLocal(this.formData.sessionDate) + " " + this.formData.sessionTime
};
let utcTime = this.$rootScope.mtz.utc(timeZoneInfo.selectedDateTime).utcOffset(timeZoneInfo.utcOffset).format("YYYY-MM-DD HH:mm");
let localTime = this.$rootScope.mtz.utc(utcTime).toDate();
localTime = this.$rootScope.mtz(localTime).format("YYYY-MM-DD HH:mm");
return localTime;
}
So when values are selected I am showing label that says: Your local time
And underneath I want to show result from convertSelectedTimeZoneToClients()that will be basically string in 'YYYY-MM-DD HH:mm' format.
Can I preform something like this on the html as well or I will have to move to controller? What is the best or easiest way to accomplish this?
I have tried ng-value, but I guess I am doing wrongly. Nothing gets show, but I do not get any errors in console as well.
in your function you can check if your drop downs are selected, then calculate and return result
$scope.getData = function () {
if ($scope.ValueOfFirstDropDown != undefined && $scope.ValueOfSecondDropDown != undefined && $scope.ValueOfThirdDropDown != undefined) {
//calculate result
return result;
}
}
and in your html
<label>{{getData()}}</label>
Try this:
<div ng-bind="convertSelectedTimeZoneToClients()"></div>
You should call this function on change of selected value
<select ng-change="convertSelectedTimeZoneToClients();"></select>
<div class="col-md-2"
ng-show="newTestSessionCtrl.formData.sessionTime && newTestSessionCtrl.formData.timeZone && newTestSessionCtrl.formData.sessionCloseInterval">
<lable>Your local time</lable>
<div ng-bind="clientDateTimeZone"></div>
</div>
and reflect $scope.clientDateTimeZone = yourreturnedvalue
No need to return any thing
$scope.convertSelectedTimeZoneToClients = function() {
let timeZoneInfo = {
usersTimeZone: this.$rootScope.mtz.tz.guess(),
utcOffset: this.formData.timeZone.offset,
selectedDateTime: this.toJSONLocal(this.formData.sessionDate) + " " + this.formData.sessionTime
};
let utcTime = this.$rootScope.mtz.utc(timeZoneInfo.selectedDateTime).utcOffset(timeZoneInfo.utcOffset).format("YYYY-MM-DD HH:mm");
let localTime = this.$rootScope.mtz.utc(utcTime).toDate();
localTime = this.$rootScope.mtz(localTime).format("YYYY-MM-DD HH:mm");
//set It here
$scope.clientDateTimeZone = localTime
//return localTime;
}

If date greater than now add class via jQuery

HTML:
<div class="date">
<strong>21</strong>
<span class="month">Jan</span>
<strong class="year">15</strong>
<span class="details"></span>
</div>
JS:
var selectedDate = $('.events-list .date').text();
var now = new Date();
if (selectedDate < now) {
$('.event').addClass('past');
}
But not add class to event. Whats my problem?
You'll have to convert the strings individually into a format that javascript can parse to create a date object from it. Something like this http://jsfiddle.net/uew2j1pu/1/
<div class="date">
<strong class="day">5</strong>
<span class="month">Jan</span>
<strong class="year">15</strong>
<span class="details"></span>
Script:
var day = $('.day').text();
var month = $('.month').text();
var year = $('.year').text();
var fullDate = new Date('20'+year+'-'+month+'-'+day);
var now = new Date();
if (fullDate < now) {
$('.event').addClass('past');
}
You said:
If date greater than now add class via jQuery
and in your code it says:
if (selectedDate < now) {
maybe you should write it like this way:
if (selectedDate > now) {
if that's what you want.

JavaScript that prints date and time with a link won't work

I'm currently enrolled in a JavaScript class at my community college, and we're supposed to create a page with the following:
"Today's date is (date)"
"Kids Club"
"The time is (time)"
Then, I don't seem to get this part, the instructions state: "Have a link to the new kidsnew.htm page that contains the text "Go To Kids Club". Use onClick and widow.location to open kidsnew.htm.
Before switching, you should use the navigator object and the method to test for the name and version of the browser. Display the name and version of the browser with an alert box and advise the user to upgrade for better results with the new page if their browser is out of date.
The kidsnew page should contain an HTML form button that will take you back to the "kidsold.htm" page."
So. I assume that I'll need the browser verification, where you can find in the first part of the code. I don't get what else I'm supposed to be using, as we were not told of a "onClick" method in the chapter's were reading. Can anyone help me refine the code and get it to display as stated? I did most of it correctly, I think;
Here's my code:
<html>
<head>
<title>Kids Club</title>
<script type = "text/javascript" src = "brwsniff.js"></script>
<script type = "text/javascript">
<!-- hide me from older browsers>
//==============================Browser Info=================================
var browser_info = getBrowser();
var browser_name = browser_info[0];
var browser_version = browser_info[1];
var this_browser = "unknown";
if (browser_name == "msie")
{
if(browser_version < 5.5)
{
this_browser = "old Microsoft";
}
else
{
this_browser = "modern";
}
}
//end
if (browser_name == "netscape")
{
if (browser_version < 6.0){
this_browser = "old Netscape";
else
{
this_browser = "modern";
}
} //end
</script>
//=========================End Browser Info============================
//==========================Start Date Script============================
var date = new Date();
//new is keyword for object Date
//
//getting info from object Date
//
var month = date.getMonth();
var day = date.getDate();
var year = date.getYear();
var hour = date.getHours();
var minutes = date.getMinutes();
//january is month 0, think of arrays
//
month = month + 1;
//fix y2k
//
year = fixY2k(year);
//fix minutes by adding 0 infrotn if less than 10
//
minutes = fixTime(minutes);
var date_string = month + "/" + day + "/" + year;
var time_string = hour + ":" + minutes;
var date = "Today is " + date_string";
var time = "The time is " + time_string;
//y2k fix
//
function fixY2k(number) {
if (number < 1000){
number = number + 1900;
return number;
}
//time fixer
//
function fixTime(number){
if(number < 10) {
number = "0" + number;
}
return number;
}
//========================End Time Script==================================
// show me -->
</script>
</head>
<body>
<script type = "text/javascript">
<!-- hide me from older browsers
document.write(date);
</script>
//show me -->
<h1>Kids Club</h1>
<script type = "text/javascript">
<!-- hide me from older browsers
document.write(time);
</script>
//show me -->
</body>
</html>
Some comments:
> <script type = "text/javascript">
> <!-- hide me from older browsers>
That's rubbish, HTML comment delimiters were never needed to hide script element content, just remove them.
> var year = date.getYear();
You should use the getFullYear method, it avoids the two digit year issue.
> var date = "Today is " + date_string";
There is no need to declare date a second time. It's not harmful, just unnecessary. date started out as a Date object, now it's a string. That's not good programming style, just modify the existing date_string, e.g.
date_string = "Today is " + date_string";
In the body of the page you have:
> <script type = "text/javascript">
> <!-- hide me from older browsers
> document.write(date);
> </script>
> //show me -->
Note that the comment delimiters start inside the script element, then finish outside it. So the browser is left with invalid HTML and whatever happens next is a result of error correction (the same for the next script element too).
Fix that and you may have solved your problem.

Categories