Error while Importing Moment.js to HTML Document - javascript

When I try to import Moment.js to a HTML document using
<script src="https://unpkg.com/moment#2.29.4/min/moment.min.js"></script>
I get this message in browser console every time: (Both tested in Firefox and Chrome)
Uncaught Error: failed to require "moment/moment"
What causes this error?
I've tried CDNJS, Unpkg and JSDelivr. I've also tried previous versions of Moment.js.

It would appear that the problem is within the moment-jalaali library. As an alternative, you could try the jalaali-moment library (some of the moment-jalaali authors are involved as well).
For testing purposes, you can try this fiddle - your code has been adapted to use the jalaali-moment library. The fiddle contents are also in the following SO snippet.
var d = new Date()
var jalaali = new Intl.DateTimeFormat('en-AU-u-ca-persian', {
year: 'numeric',
month: 'numeric',
day: 'numeric',
timeZone: 'Europe/Istanbul'
}).format(d).split('/');
var hijri = new Intl.DateTimeFormat('en-AU-u-ca-islamic-umalqura', {
year: 'numeric',
month: 'numeric',
day: 'numeric',
timeZone: 'Europe/Istanbul'
}).format(d).split('/');
var month = parseInt(hijri[1]);
switch (month) {
  case 1:
month = 'Muyaram';
    break;
  case 2:
month = 'Safar';
break;
  case 3:
month = 'Rabamah';
break;
  case 4:
month = 'Rabafer';
    break;
  case 5:
month = 'Jazamah';
break;
  case 6:
month = 'Jazafer';
break;
case 7:
month = 'Rajab';
    break;
  case 8:
month = 'Shaban';
    break;
  case 9:
month = 'Ramadan';
break;
  case 10:
month = 'Shawil';
break;
  case 11:
month = 'Zulqat';
break;
case 12:
month = 'Zulgach';
}
var jalaaliMoment = moment(d, 'jD/jM/jYYYY');
var result = hijri[0] + '/' + jalaaliMoment.jDayOfYear() + ' ' + month + ' ' + jalaali[2];
document.getElementById("dt").innerHTML = result;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Irshatovan Calendar</title>
</head>
<body>
<h2 id="dt"></h2>
<script src="https://unpkg.com/moment#2.29.4/min/moment.min.js"></script><!-- Moment.js importing problem. -->
<script src="https://unpkg.com/jalali-moment/dist/jalali-moment.browser.js"></script>
</body>
</html>

Related

How can I include values in my javascript populated drop down list to include in a price calculator?

Here is my code sample:
<script>
const td=new Date(); // set Date object td to today
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
td.setDate(td.getDate()+3)
ndays = td - new Date();
let deadline = td.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
document.cookie = "ndays = " + ndays;
offset = td.getTimezoneOffset();
const opts=[...Array(18)].map(_=>{ // generate an Array of 7 (empty) elements
let r=td.toLocaleString("en-us",{weekday: 'long', year: 'numeric', month: 'long', day: 'numeric'}) + " # "+deadline+" "+timezone+" Time ("+ Math.round(ndays/60/60/24/1000) + " days)"; // format date td
td.setDate(td.getDate()+1); // increment td by one calendar day
ndays = td - new Date();
return r // return date string to opts array
})
</script>
<select name="deadline" id="deadline" class="form-control" required="required">
<script>
document.querySelector("select").innerHTML=opts.map(o=>`<option>${o}</option>`).join("") // make options
</script>
</select>
I need to be able to add incremented values based on the deadline selected to include in a pricing calculation. For example, if the order is:
15 or more days: the price would be $10 per unit (a factor of 1)
10 to 14 days: it would be $12 per unit (a factor of 1.2)
7 days: $13 per unit (a factor of 1.3)
5 days: $14 (a factor of 1.4)
3 days: $15 (a factor of 1.5)
You're using document.querySelector("select").innerHTML to write a string of the options to the <select> element. First add the days to the opts array:
const opts=[...Array(18)].map(_=>{
let numdays = Math.round(ndays/60/60/24/1000);
//...
ndays = td - new Date();
return [numdays, r];
});
...then, when looping it, add the days to the option value and text to the option element:
document.querySelector("select").innerHTML = opts.map(([d,o])=>`<option value="${d}">${o}</option>`).join("");
Use the document.querySelector("select") change event listener to implement your pricing calculator.
All together:
// WRITE DATE OPTIONS ARRAY
const opts = writeDateOptions();
// WRITE DATE OPTIONS TO SELECT ELEMENT
const sel = document.getElementById("deadline");
sel.innerHTML = "<option></option>" + opts.map(([d,o])=>`<option value="${d}">${o}</option>`).join("");
// GET DAYS AND FACTOR ON SELECT CHANGE EVENT
sel.addEventListener("change", function (evt) {
let days = parseInt(evt.target.options[evt.target.selectedIndex].value);
let factor = 0;
switch (days) {
case 3: case 4: factor = 1.5; break;
case 5: case 6: factor = 1.4; break;
case 7: case 8: case 9: factor = 1.3; break;
case 10: case 11: case 12: case 13: case 14: factor = 1.2; break;
case 15: default: factor = 1.0;
}
// price calculator here?
document.getElementById("daysfactor").innerText
= days + " days, "
+ factor + " factor";
});
// this is a simply a function wrapped around the date/options array code to be able to move it to the bottom of the code so as to emphasize the bulk of the additional code
function writeDateOptions () {
const td=new Date(); // set Date object td to today
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
td.setDate(td.getDate()+3);
ndays = td - new Date();
let deadline = td.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
//document.cookie = "ndays = " + ndays; // stackoverflow doesn't like no one messin' with her cookies
offset = td.getTimezoneOffset();
// return days/desc options array
return [...Array(18)].map(_=>{
let numdays = Math.round(ndays/60/60/24/1000);
let r=td.toLocaleString(
"en-us", {weekday: 'long', year: 'numeric', month: 'long', day: 'numeric'}
) + " # "+deadline+" "+timezone+" Time ("+ numdays + " days)"; // format date td
td.setDate(td.getDate()+1); // increment td by one calendar day
ndays = td - new Date();
return [numdays, r]; // return days and date string to opts array
});
}
<select name="deadline" id="deadline" class="form-control" required="required"></select>
<div id="daysfactor"></div>
OR, create each option element and add the value and text content while looping your dates array.
// replace vvvv
// document.querySelector("select").innerHTML = opts.map(([d,o])=>`<option value="${d}">${o}</option>`).join("");
// with vvvv
// ADD OPTIONS WITH VALUES AND TEXT TO SELECT
const sel = document.querySelector("select");
sel.appendChild(document.createElement("option")); // blank option first
opts.forEach(function ([numdays, desc]) {
let opt = document.createElement("option");
opt.value = numdays;
opt.textContent = desc;
sel.appendChild(opt);
});

Bootstrap-table2 How to make custom text search filter on String month and date?

I am currently making a BootstrapTable with one column with a dataField of birthday, which is a string in the format of "day/month" or "3/10" for October 3rd as an example. I successfully made a formatter which transformed every string like "3/10" to show up as a string like "October 3rd" on the table. I want to add a filter: textFilter and currently using a default. The problem is, if the user types in "October", nothing shows up. You type in "10" for October 3rd to show up. I am trying to implement a custom filter such that if if the user types in a substring like "Octo", all examples of October birthdays would show up and non October dates would be filtered. How can I implement something like this? This is my first attempt at trying to implement something like this below.
filterByPrice = (filterVal, data) => {
if (filterVal) {
var fields = data.birthday.split('/');
var month = parseInt(fields[1]);
var day = parseInt(fields[0]);
switch(month){
case 1:
month = "January";
break;
case 2:
month = "February";
break;
case 3:
month = "March";
break;
case 4:
month = "April";
break;
case 5:
month = "May";
break;
case 6:
month = "June";
break;
case 7:
month = "July";
break;
case 8:
month = "August";
break;
case 9:
month = "September";
break;
case 10:
month = "October";
break;
case 11:
month = "November";
break;
case 12:
month = "December";
}
var dateString = month + " " + day
data.filter(dateString.includes(filterVal));
}
return data;
const {columns} = {
columns: [{
dataField: 'birthday',
text: 'Birthday',
filter: textFilter({
onFilter: this.birthdayFilter
}),
formatter: birthdayFormatter, //successfuly transforms "10/3" into "October 3rd" function.
}]
}
I figured it out. Turns out there is a parameter called filterValue that searches based on the formatter.
{
dataField: 'birthday',
text: 'Birthday',
filter: textFilter(),
filterValue: birthdayFormatter,
formatter: birthdayFormatter
}

php Date Conversion to javaScript

Needs help in rewriting this php code in JavaScript
$date='20170721';
$stamps = strtotime($date);
$newdate = date('d M Y',$stamps);
$data = explode(' ', $newdate);
echo $data[0].' '.strtoupper($data[1]).' '.$data[2];
//output 2017 JUL 21
I am new in JavaScript this is what i have done so far
var date='20170721';
varstamps = strtotime($date);
var newdate = date('d M Y',$stamps);
var data = explode(' ', $newdate);
$data[0].' '.strtoupper($data[1]).' '.$data[2];
For better Result you can user https://momentjs.com/ Moment js
include moment js using
<script type="text/javascript" src="bower_components/moment/moment.js"></script>
var date = '20170721';
moment(date).format('YYYY MMM DD');
Here's a solution
var date = '20170721';
var year = date.slice(0,4),
month = date.slice(4,6),
day = date.slice(-2);
// create new Date obj
date = new Date(year, month, day);
// format using toLocaleDateString
console.log(new Date(year, month, day).toLocaleDateString('en-GB'));
// custom format
console.log(date.getFullYear() + ' ' + (date.getMonth()) + ' ' + date.getDate())
//output 2017 JUL 21
Php :
$date='20170721';
$stamps = strtotime($date);
Javascript :
var idate = 1500588000; // unix timestamp returned from php ($stamps variable)
var jdate = new Date(idate * 1000);
var day = jdate.getDate();
var month = jdate.getMonth();
var year = jdate.getYear();
var fulldate = jdate.toDateString();
Reference : Javascript Date - set just the date, ignoring time?
Currently i dont think javascript supports date conversions as this, but heres a work around
var str='20170721';
var datee=str.slice(0,4)+'-'+str.slice(4,6)+'-'+str.slice(6,8);
var date = new Date(datee);
var newDate = date.toString('yyyy MMMM dd');
console.log(newDate);
// Or you can decide to do this without any external library
var num =parseInt(str.slice(4,6));
var month='';
switch(num)
{
case 0:
month="January";
break;
case 1:
month="February";
break;
case 2:
month="March";
break;
case 3:
month="April";
break;
case 4:
month="May";
break;
case 5:
month="June";
break;
case 6:
month="July";
break;
case 7:
month="August";
break;
case 8:
month="September";
break;
case 9:
month="October";
break;
case 10:
month="November";
break;
case 11:
month="December";
break;
default:
month="Invalid month";
}
console.log(str.slice(0,4)+' '+month+' '+str.slice(4,6));
<script src="http://cdnjs.cloudflare.com/ajax/libs/datejs/1.0/date.min.js"></script>

jQuery calendar opening and closing times

I have attached a calendar and opening on my site but it doesn't seem to be working don't know why here is the code.
<script type="text/javascript">
switch(curday){
case 0:
day = "sunday";
break;
case 1:
day = "<h2>Monday</h2><br/>9:00-12:00 <br/> 12:00-13:00 Lunch<br/> 13:00-19:00<br/>";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "<h2>Wednesday</h2><br/>9:00-12:00 <br/> 12:00-13:00 Lunch<br/> 13:00-19:00<br/>";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "<h2>Friday</h2><br/>9:00-12:00 <br/> 12:00-13:00 Lunch<br/> 13:00-19:00<br/>";
break;
case 6:
day = "Saturday" "We are closed" ;
break;
}
document.write(day);
</script>
and this is code for the calender
<script type="text/javascript">
var todaydate=new Date()
var curmonth=todaydate.getMonth()+1 //get current month (1-12)
var curyear=todaydate.getFullYear() //get current year
document.write(buildCal(curmonth ,curyear, "main", "month", "daysofweek", "days", 1));
</script>

Javascript date format without timezone

I have a javascript variable which is defined from an input value.
$d = $('#date').val();
$myDateParts = $d.split("-");
$dflip = new Date($myDateParts[2], ($myDateParts[1]-1), $myDateParts[0]);
console.log($dflip);
$dflip = Wed Sep 19 00:00:00 UTC+0100 2012
How can i format the output to just:
Wed Sep 19
You can do something using substring or toDateString or both
for e.g:
var dateString = new Date(2012, 0, 31).toDateString();
var noYear = dateString.substring(0, dateString.length-5);
console.log(noYear);
Try with following code.
<script src="../../ui/jquery.ui.datepicker.js"></script>
$( "#datepicker" ).datepicker( "D M yy", dflip.val());
This may not be the cleanest, most efficient or best way to accomplish what you're looking for, but I created a function to return the date without the timezone. You can adjust the "theDate" variable to return only the parts of the date you want.
function properDate(){
var d = new Date();
var DayOfMonth = d.getDate();
var DayOfWeek = d.getDay();
var Month = d.getMonth();
var Year = d.getFullYear();
var Hours = d.getHours();
var Minutes = d.getMinutes();
var Seconds = d.getSeconds();
switch (DayOfWeek) {
case 0:
day = "Sun";
break;
case 1:
day = "Mon";
break;
case 2:
day = "Tue";
break;
case 3:
day = "Wed";
break;
case 4:
day = "Thu";
break;
case 5:
day = "Fri";
break;
case 6:
day = "Sat";
break;
}
switch (Month) {
case 0:
month = "Jan";
break;
case 1:
month = "Feb";
break;
case 2:
month = "Mar";
break;
case 3:
month = "Apr";
break;
case 4:
month = "May";
break;
case 5:
month = "Jun";
break;
case 6:
month = "Jul";
break;
case 7:
month = "Aug";
break;
case 8:
month = "Sep";
break;
case 9:
month = "Oct";
break;
case 10:
month = "Nov";
break;
case 11:
month = "Dec";
break;
}
var theDate = day + " " + month + " " + DayOfMonth + " " + Year + " " + Hours + ":" + Minutes + ":" + Seconds;
return theDate;
}
My DateExtentions library will do that - although it may be overkill if all you're doing is that one, simple format.
http://depressedpress.com/javascript-extensions/dp_dateextensions/
I can parse the date based on a passed mask and format the output however you like (it'll also do all sorts of date math and utility stuff so again, it might be heavier than you need).

Categories