This question already has answers here:
JavaScript hoisting explanation
(4 answers)
Closed 3 years ago.
I have a GlobalFunction.js file with this.
function day(day) {
switch(day) {
case 0:
return "Sunday";
case 1:
return "Monday";
case 2:
return "Tuesday";
case 3:
return "Wednesday";
case 4:
return "Thursday";
case 5:
return "Friday";
case 6:
return "Saturday";
}
}
function month(month) {
switch(month) {
case 0:
return "January";
case 1:
return "February";
case 2:
return "March";
case 3:
return "April";
case 4:
return "May";
case 5:
return "June";
case 6:
return "July";
case 7:
return "August";
case 8:
return "September";
case 9:
return "October";
case 10:
return "November";
case 11:
return "December";
}
}
function styleTime(time) {
time = time[1].split(':');
// fetch
var hours = Number(time[0]);
var minutes = Number(time[1]);
var seconds = Number(time[2]);
// calculate
var timeValue;
if (hours > 0 && hours <= 12) {
timeValue= "" + hours;
} else if (hours > 12) {
timeValue= "" + (hours - 12);
} else if (hours == 0) {
timeValue= "12";
}
timeValue += (minutes < 10) ? ":0" + minutes : ":" + minutes; // get minutes
timeValue += (hours >= 12) ? " P.M." : " A.M."; // get AM/PM
return timeValue;
}
function nth(d) {
if (d > 3 && d < 21) return 'th';
switch (d % 10) {
case 1: return "st";
case 2: return "nd";
case 3: return "rd";
default: return "th";
}
}
function styleDate(date) {
var verifyDay = new Date(date[0]);
var dayOfWeek = day(verifyDay.getDay()); //prints monday, tuesday, wednesday, etc
var year = verifyDay.getFullYear(); // prints the year
var month = month(verifyDay.getMonth());
var day = verifyDay.getDate();
var date = day + nth(verifyDay.getDate());
return dayOfWeek + ", " + month + " " + date + " " + year;
}
export function styleDateTime(dateString) {
var dateTime = dateString.split(" ");
return styleDate(dateTime) + " at " + styleTime(dateTime);
}
// default export
export default function() {
return 'default';
}
I import this into a js file like so.
import { styleDateTime } from "../GlobalFunctions"
I use it like so:
{styleDateTime(array.date)}
In the styleDate function, it tells me that day is not a function. why?
Because inside styleDate method you are creating a new variable with same name as day and that's why you are not able to access the day method. Use a different variable name, it will work.
Write it like this:
function styleDate(date) {
var verifyDay = new Date(date[0]);
var dayOfWeek = day(verifyDay.getDay()); //prints monday, tuesday, wednesday, etc
var year = verifyDay.getFullYear(); // prints the year
var month = month(verifyDay.getMonth());
// here
var new_day = verifyDay.getDate();
var date = new_day + nth(verifyDay.getDate());
return dayOfWeek + ", " + month + " " + date + " " + year;
}
It's because your local day variable in styleDate is shadowing the function defined outside of it. Rename it to something else.
If you think it shouldn't be shadowed because it's defined after the first usage, JavaScript applies hoisting which moves all the declarations to the beginning of the function, setting them to undefined until they are later set.
function styleDate(date) {
...
var myDay = verifyDay.getDate();
var date = myDay + nth(verifyDay.getDate());
...
Related
I've started using UglifyJS, and the way it nested some of the if statements within the switch expression was peculiar. I'm struggling to find any documentation on it. Neither Mozilla nor W3Schools say anything explicit about it. The script is running fine, I would just like to know more about how.
Global variable:
var today = new Date();
Original script:
function date(date = today) {
if (date !== today) { date = new Date(date) };
var year = date.getFullYear().toString(),
month = (date.getMonth() + 1).toString(),
day = date.getDate().toString(),
shortDay,
longDay;
if (month.length === 1) { month = "0" + month };
if (day.length === 1) { day = "0" + day };
switch (date.getDay()) {
case 0: shortDay = 'Sun'; longDay = "Sunday"; break;
case 1: shortDay = 'Mon'; longDay = "Monday"; break;
case 2: shortDay = 'Tue'; longDay = "Tuesday"; break;
case 3: shortDay = 'Wed'; longDay = "Wednesday"; break;
case 4: shortDay = 'Thu'; longDay = "Thursday"; break;
case 5: shortDay = 'Fri'; longDay = "Friday"; break;
case 6: shortDay = 'Sat'; longDay = "Saturday"; break;
};
return {
full: year + '-' + month + '-' + day + ' ' + shortDay,
mmddyyyy: month + '/' + day + '/' + year,
mmddyy: month + '/' + day + '/' + year.substring(2),
md: (date.getMonth() + 1).toString() + '/' + date.getDate().toString(),
year, month, day, shortDay, longDay
};
};
UglifyJS compressed script (reformatted for readability):
function date(date = today) {
var shortDay, longDay,
year = (date = date !== today ? new Date(date) : date).getFullYear().toString(),
month = (date.getMonth() + 1).toString(),
day = date.getDate().toString();
switch (1 === month.length && (month = "0" + month), 1 === day.length && (day = "0" + day), date.getDay()) {
case 0: shortDay = "Sun", longDay = "Sunday"; break;
case 1: shortDay = "Mon", longDay = "Monday"; break;
case 2: shortDay = "Tue", longDay = "Tuesday"; break;
case 3: shortDay = "Wed", longDay = "Wednesday"; break;
case 4: shortDay = "Thu", longDay = "Thursday"; break;
case 5: shortDay = "Fri", longDay = "Friday"; break;
case 6: shortDay = "Sat", longDay = "Saturday"
}
return {
full: year + "-" + month + "-" + day + " " + shortDay,
mmddyyyy: month + "/" + day + "/" + year,
mmddyy: month + "/" + day + "/" + year.substring(2),
md: (date.getMonth() + 1).toString() + "/" + date.getDate().toString(),
year: year, month: month, day: day,
shortDay: shortDay, longDay: longDay
}
}
I believe that this is the part that is the most peculiar:
switch (1 === month.length && (month = "0" + month), 1 === day.length && (day = "0" + day), date.getDay()) {
case 0: shortDay = "Sun", longDay = "Sunday"; break;
case 1: shortDay = "Mon", longDay = "Monday"; break;
case 2: shortDay = "Tue", longDay = "Tuesday"; break;
case 3: shortDay = "Wed", longDay = "Wednesday"; break;
case 4: shortDay = "Thu", longDay = "Thursday"; break;
case 5: shortDay = "Fri", longDay = "Friday"; break;
case 6: shortDay = "Sat", longDay = "Saturday"
}
Comma operator
First of all, there is a comma operator in JavaScript which always returns the last element.
For example:
const x = (1, 2, 3, 4, 5)
console.log(x) // 5
So this:
switch (1 === month.length && (month = "0" + month), 1 === day.length && (day = "0" + day), date.getDay()) {
Looks exactly like this:
switch (date.getDay()) {
From the switch's point of view.
&& operator
Also, && operator stops if the left operand is falsy:
false && console.log('something') // doesn't log anything
true && console.log('something') // logs something
So:
// month is equal to '0' + month, but only if 1 === month.length
1 === month.length && (month = "0" + month)
// same here
1 === day.length && (day = "0" + day)
var day = "Sunday";
var x;
switch (day) {
case 0:
var x = 5;
day = "Sunday";
break;
case 1:
day = "Monday";
break;
}
document.getElementById("demo").innerHTML = "Today is " + day + " " + x;
<p id="demo"></p>
I want to get output as Today is Sunday 5
but I am getting the output as Today is Sunday undefined
How can get the value as 5 instead of undefined???
it is because of mistake in switch statement you are using number instead of day
like case 0: instead of case "sunday"
that is the mistake
var day = "Sunday";
var x;
switch (day) {
case "Sunday":
var x = 5;
day = "Sunday";
break;
case "Monday":
day = "Monday";
break;
}
document.getElementById("demo").innerHTML = "Today is " + day + " " + x;
<p id="demo"></p>
you can try like this too with numbers
The getDay() method returns the weekday as a number between 0 and 6.
(Sunday=0, Monday=1, Tuesday=2 ..)
This example uses the weekday number to calculate the weekday name:
<p id="demo"></p>
<script>
var day;
var x=0;
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
document.getElementById("demo").innerHTML = "Today is " + day + x;
</script>
How can get the value as 5 instead of undefined???
variable in javascript will be initialized to undefined .so is out puts undefined because it didn't set to 5 in switch case (fails in condition to assing)
Answer is pretty simple:
switch (day) {
case 0:
var x = 5;
day = "Sunday";
break;
case 1:
day = "Monday";
break;
}
In the above code switch(day) you are passing a string "Sunday " and in cases matching it with an int type like case 0,it is not possible so try to pass an int in switch() or use case like case "Sunday":
switch (day) {
case "Sunday":
var x = 5;
day = "Sunday";
break;
case "anyday"://use case as you want
day = "anyday";
break;
}
You might find it easier to use an object to hold a set of keys/values. You can then check the object using the value held in day.
const days = {
sunday: 5,
monday: 2
};
let day = "Sunday";
const demo = document.getElementById('demo');
demo.innerHTML = "Today is " + day + " " + days[day.toLowerCase()];
<p id="demo"></p>
I have a calendar widget which is working OK. The problem I have is when selecting a date - the code doesn't find the field I want to set to the selected date, and I can't see why not.
<xp:panel id="calendarHolder">
<script>
require([ "dijit/Calendar", "dojo/date", "dojo/domReady!", "dijit/registry" ],
function(Calendar, date){
new Calendar({ value: new Date(),
onValueSelected: function(date){calendarDateClicked(date);
}},"mycal");
//Set month in correct format
function setMonth(month){
switch(month)
{
case 1:
month = "Jan";
break;
case 2:
month = "Feb";
break;
case 3:
month = "Mar";
break;
case 4:
month = "Apr";
break;
case 5:
month = "May";
break;
case 6:
month = "Jun";
break;
case 7:
month = "Jul";
break;
case 8:
month = "Aug";
break;
case 9:
month = "Sep";
break;
case 10:
month = "Oct";
break;
case 11:
month = "Nov";
break;
case 12:
month = "Dec";
break;
}
return month;
}
//create Click action
function calendarDateClicked(date){
var d = new Date(date);
var month = (d.getMonth() + 1);
month = setMonth(month);
var day = '' + d.getDate() + ",";
var year = d.getFullYear();
var dateString = [month,day,year].join(" ");
dojo.byId('#{id:hiddenCalWidgetSelectedDate}').value = dateString
dojo.byId('#{id:calDate}').value = dateString;
XSP.partialRefreshPost("#{id:mainPanel}",{
onComplete: function() {
XSP.partialRefreshGet("#{id:sideViews}", {});
}
});//Post Value to server
}
});
</script>
<div id="mycal">
</div>
<div id="textbox">
<xp:inputText id="hiddenCalWidgetSelectedDate"
style="display:block;" value="#{sessionScope.selectedDate}">
<xp:this.defaultValue><![CDATA[#{javascript://
var d = new Date(/*Today*/);
var month = '' + (d.getMonth() + 1);
var day = '' + d.getDate();
var year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return [day,month,year].join("/"); }]]></xp:this.defaultValue>
</xp:inputText></div>
</xp:panel>
The error I get is dojo.byId('#{id:hiddenCalWidgetSelectedDate}') is null
Any help would be appreciated.
Graeme
If you add a normal script block to an XPage, the EL will not get resolved.
You have to add your code inside a xp:scriptBlock.
In HTMl How can I change the format of date? Using date() I got today's date.The problem is I don't know how to change the format of the date. I have to display the date format like this "May 28th 2013". Can any one help me ???
<html position="0,0,0,0" canExport="false">
<![CDATA[
<script>
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var monthname ;
if (month == 1)
monthname = "Jan";
else if (month == 2)
monthname = "Feb";
else if (month == 3)
monthname = "Mar";
else if (month == 4)
monthname = "Apr";
else if (month == 5)
monthname = "May";
else if (month == 5)
monthname = "June";
else if (month == 7)
monthname = "July";
else if (month == 8)
monthname = "Aug";
else if (month == 9)
monthname = "Sep";
else if (month == 10)
monthname = "Oct";
else if (month == 11)
monthname = "Nov";
else
monthname = "Dec";
var day = currentTime.getDate();
var dayname;
if (day == 2 ||day == 22 )
dayname = "nd";
else if (day == 3 ||day == 23 )
dayname = "rd";
else if (day == 1 ||day == 21||day == 31 )
dayname = "st";
else
dayname = "th";
var year = currentTime.getFullYear();
s = currentTime.toDateString();
alert(s);
$('[name=DateDynamic]').text(monthname+" "+day+""+dayname+" "+ year);
</script>
]]>
</html>
Currently I am following the above big method.I know there should be some simple method.
I believe you want this for javascript? Don't you? Assuming your tags
Try something like:
Javascript code:
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
month = getMonthName(month);
var year = currentDate.getFullYear()
document.write("<b>" +month + " " + day + " " + year + "</b>")
function getMonthName(monthNumber)
{
var monthName = "";
switch (monthNumber)
{
case 5:
monthName = "May";
break;
default:
monthName ="not implemented yet";
break;
}
return monthName;
}
Edit--->
I see you have changed your tags. I lieve it up here for anyone!
You can do this using different languages, but I'm guessing you want to use the Date object in Javascript if you're wanting to display a simple date when the page loads.
Here's a tutorial on the many ways to format dates using Javascript:
http://www.w3schools.com/js/js_obj_date.asp
I think the Javascript method toDateString might be want you are looking for:
Documentation
var now = new Date();
x = now.toDateString();
//Fri May 31 2013
//Additional Formatting
var patt = /(\w+) (\w+ [0-9]{1,2}) ([0-9]{4})/;
x = x.replace(patt, '$2, $3');
//May 31, 2013
I put together a Fiddle to handle your 'day suffix' issue.
Output of Fiddle:
//May 31st, 2013
var myDate = new Date();
var formattedDate = myDate.toDateString().split(' ')
formattedDate[0] = '';
if (formattedDate[2][0] != 1 && formattedDate[2][1] == 1) {
formattedDate[2] = formattedDate[2] + 'st';
} else if (formattedDate[2][0] != 1 && formattedDate[2][1] == 2) {
formattedDate[2] = formattedDate[2] + 'nd';
} else if (formattedDate[2][0] != 1 && formattedDate[2][1] == 3) {
formattedDate[2] = formattedDate[2] + 'rd';
} else {
formattedDate[2] = formattedDate[2] + 'th';
}
formattedDate = formattedDate.join(' ');
Output for today: May 31st 2013
http://jsfiddle.net/VHqpU/2/
Based on your example, I cleaned it up a bit. You were also using getDate() for you "day" variable instead of getDay().
<script type="text/javascript">
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var months = ["Dec","Jan","Feb","Mar","Apr","May","June","July","Aug","Sep","Oct","Nov",];
var monthname = months[month];
var day = currentTime.getDay();
var dayname;
if (day == 2 ||day == 22 )
dayname = "nd";
else if (day == 3 ||day == 23 )
dayname = "rd";
else if (day == 1 ||day == 21||day == 31 )
dayname = "st";
else
dayname = "th";
var year = currentTime.getFullYear();
alert(monthname+" "+day+""+dayname+" "+ year);
$('[name=DateDynamic]').text(monthname+", "+day+""+dayname+" "+ year);
</script>
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).