JavaScript - convert to string using array index - javascript

I got this code from a book and I don't understand how this statement "mm=months[mm]" convert to month name string:
function init(){
var panel = document.getElementById("panel");
var days=["sun","mon","tue","wed","thur","fri","sat"];
var months=["jan","feb","mar","apr","may","jun",
"jul","aug","sep","oct","nov","dec"];
var now = new Date();
var yy = now.getFullYear();
var mm = now.getMonth();
var dd = now.getDate();
var dy = now.getDay();
mm=months[mm]; //convert to month name string
dy=days[dy]; //convert to month name string
var str = dy+","+mm","+dd+","+yy;
panel.innerHTML+="us date string: "+str;
str = dy+","+dd+" "+mm+","+yy;
panel.innerHTML+="<br>uk date string: "+str;
}
window.onload=init();
My question is this what exactly does the mm=months[mm] and dy=days[dy] (convert to month or day name string) do. I don't understand how this statement "mm=months[mm]" convert to month name string, when months is an array. Is this just some build in function of an array?

mm is a number at the beginning of the statement mm=months[mm], so therefore it returns the mmth value in the months array which is a string. In JavaScript variables are not strictly typed so it then inserts this string into the variable mm

mm is a number from 0-11 that represents the month specific to the date object you retrieved it from. months is an array containing the names of all the months. If you say mm = months[mm], you're saying that mm equals the string at position mm in the months array. It's confusing, because they're using the same variable name. It might have been better to do something like this:
var mm = now.getMonth();
alert(mm); // will alert 6
var monthName = months[mm]; // will alert July, which is position 7 in the months array
The reason mm is six is because the months for some reason are 0-indexed, meaning they start at 0 and go to 11; January would be 0, and December 11.

days is an array. Given index dy=0, days[dy] returns "sun", which is the 0th value in the array. Similarly, given index dy=1, days[dy] returns "mon", which is the 1st value in the array. And so on.
Same concept for months.
But the correct answer should be "use some built-in function in Javascript or jQuery". See this post for more details. Rolling your own datetime conversion functions is almost certainly going to come back and bite you in the long run.

Assume the date is 08 and month is july .
var yy = now.getFullYear();
var mm = now.getMonth(); // month is 7 now
var dd = now.getDate(); // dd is 8 now
var dy = now.getDay();
Now,
mm=months[mm];
means,
mm = months[7];
// in months array, at seventh index we have july,
so mm is july.
No its not converting but using value from array based on index.

mm=month[mm] take the value at the index mm (returned by now.getMonth()) in the months array and puts it in the mm variable. That id the same thing for dy=days[dy].
I recognize that the code is badly written. mm2=month[mm] and use mm2 after (instead of the "new" mm) should be written instead.

Related

Subtract working days from a date using Javascript

I'd like to use a Javascript within my zapier.com-zap. Here is what I am trying to do for five consecutive days now:
I have a date (whatever custom format you need), need to subtract two working days from it and output it to DD-MM-YYYY using Javascript. Sounds really simple, but I don't get it to work.
I hope someone out there can help me with this! Thank you very much.
I forgot to mention an essential thing, sorry. If the result is a Sunday or Saturday I need the date of the last working day (Friday).
If you're willing to use external libraries, MomentJS is a really popular tool for parsing and modifying JavaScript dates and would make this really simple:
Example 1: Subtract 2 Days and Format
var date = new Date(),
formatted = moment(date).subtract(2, 'days').format('DD-MM-YYYY');
document.getElementById('date').innerHTML = date;
document.getElementById('example').innerHTML = formatted;
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.2/moment.min.js"></script>
This example takes today's date (<span id="date"></span>), subtracts 2 days from it,
and then displays it below in the desired format (DD-MM-YYYY):
<p id="example"></p>
Example 2: Subtract 2 Working Days and Format
If by working days you mean Monday to Friday, all you'd need to do here is determine whether the day held in your date variable was a Monday or Tuesday, then adjust the value passed in to MomentJS's subtract method accordingly. We can do this using MomentJS's get day of week function:
var date = new Date(),
formatted, daysToSubtract;
switch (moment(date).day()) {
// Sunday = 3 days
case 0:
daysToSubtract = 3;
break;
// Monday and Tuesday = 4 days
case 1:
case 2:
daysToSubtract = 4;
break;
// Subtract 2 days otherwise.
default:
daysToSubtract = 2;
break;
}
formatted = moment(date).subtract(daysToSubtract, 'days').format('DD-MM-YYYY');
document.getElementById('date').innerHTML = date;
document.getElementById('example').innerHTML = formatted;
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.2/moment.min.js"></script>
This example takes today's date (<span id="date"></span>), subtracts 2 working days (Monday to Friday) from it,
and then displays it below in the desired format (DD-MM-YYYY):
<p id="example"></p>
While I agree with #James Donnelly that momentjs is awesome, here is how you can achieve your task without using an extra library. I created this helper function to do exactly what you're asking. Just pass in your date and however many days you want to add/subtract to it (-2 in your case).
function addDaysToDate(date, days)
{
var result = new Date(date);
result.setDate(result.getDate() + days);
var dd = result.getDate();
var mm = result.getMonth() + 1; // January starts at 0.
var yyyy = result.getFullYear();
if (dd < 10)
{
dd = '0' + dd
}
if (mm < 10)
{
mm = '0' + mm
}
return dd + '/' + mm + '/' + yyyy;
}

Get month name from two digit month number

I want to get month name from two digit month number (ex- 09). I tried with this code. But it doesn't work. The code give current month name only. What are the correct code for it?
var formattedMonth = moment().month('09').format('MMMM');
While there's nothing wrong with Kevin's answer, it is probably more correct (in terms of efficiency) to obtain the month string without going through a moment object.
var monthNum = 9; // assuming Jan = 1
var monthName = moment.months(monthNum - 1); // "September"
var shortName = moment.monthsShort(monthNum - 1); // "Sep"
You want to pass the month when you create the Moment object:
var formattedMonth = moment('09', 'MM').format('MMMM'); // September
moment(
'09', // Desired month
'MM' // Tells MomentJs the number is a reference to month
).format('MMMM') // Formats month as name
You need to pass the month as a number, not text - so...
var formattedMonth = moment().month(9).format('MMMM');
console.log(formattedMonth)
Result:
October
For those looking to do it and changing languages (locale), this is what I did
let month = moment().month(09).locale('pt-br').format('MMMM');

What is the proper way to create a timestamp in javascript with date string?

I have date format returned as 05-Jan, 12-feb etc.. when i convert current date using date object in javascript . I did something like this
var curr = new Date(),
curr_year = curr.getFullYear(),
curr_month = curr.getMonth(),
curr_day = curr.getDay(),
today = new Date(curr_year, curr_month, curr_day, 0, 0, 0, 0);
console.log(today);
Here the today is returned as invalid date i needed the create a timestamp which should not include minutes secs and millisecs as zero for date comparison of month and date alone based on that i can categories .Is there way to dynamically create a date and compare those dates for given format.
And when i try to convert my date string using date object it returns year as 2001. how can i compare dates based upon current year.
For eg: in php i have used mktime to create a date dynamically from given date format and compare those results. Any suggestion would be helpful. Thanks.
You can leverage the native JS Date functionality to get human-readable date strings for time stamps.
var today = new Date();
console.log( today.toDateString() ); // Outputs "Mon Feb 04 2013"
Date comparison is also built in.
var yesterday = new Date();
yesterday.setDate( yesterday.getDate() - 1);
console.log( yesterday.toDateString() ); // Outputs "Sun Feb 03 2013"
console.log( yesterday < today ); //Outputs true
You can use the other built-in methods to fine-tune this comparison to be/not be sensitive to minutes/seconds, or to set all those to 0.
You said that you used mktime() in php, so what about this?
change to this :
var curr = new Date(),
curr_year = curr.getFullYear(),
curr_month = curr.getMonth()+1,
curr_day = curr.getDay(),
today = curr_month+'/'+curr_day+'/'+curr_year;
console.log(today);
(getMonth()+1 is because January is 0)
change the :
today = curr_month+'/'+curr_day+'/'+curr_year;
to whatever format you like.
I have found a way to convert the date into timestamp i have tried as #nbrooks implemented but .toDateString has built in date comparison which works for operator < and > but not for == operator to do that i have used Date.parse(); function to achieve it. Here it goes..
var curr = new Date(),
curr_year = curr.getFullYear(),
curr_month = curr.getMonth(),
curr_day = curr.getDate(),
today = new Date(curr_year, curr_month, curr_day, 0,0,0,0);
var dob = new Date('dob with month and date only'+curr_year);
if(Date.parse(dob) == Date.parse(today)){
//Birthdays....
}
This method can be used to create a timestamp for dynamically created date.Thanks for your suggestions.

the closest Sunday before given date with JavaScript

I need to know the date for last Sunday for given date in php & javascript
Let's have a function give_me_last_Sunday
give_me_last_Sunday('20110517') is 20110515
give_me_last_Sunday('20110604') is 20110529
The full backup is done on Sundays = weekly. If I want to restore daily backup I need full (weekly) and daily backup. I need to copy backup files before restoring to temp directory so I restoring daily backup I need to know what weekly backup file I need to copy along the daily file.
My thought was to get Julian representation (or something similar) for the given date and then subtract 1 and check if it is Sunday ... Not sure if this is the best idea and how to convert given date into something I can subtract.
Based on Thomas' effort, and provided the input string is exactly the format you specified, then:
function lastSunday(d) {
var d = d.replace(/(^\d{4})(\d{2})(\d{2}$)/,'$1/$2/$3');
d = new Date(d);
d.setDate(d.getDate() - d.getDay());
return d;
}
Edit
If I were to write that now, I'd not depend on the Date object parsing the string but do it myself:
function lastSunday(s) {
var d = new Date(s.substring(0,4), s.substring(4,6) - 1, s.substring(6));
d.setDate(d.getDate() - d.getDay());
return d;
}
While the format yyyy/mm/dd is parsed correctly by all browsers I've tested, I think it's more robust to stick to basic methods. Particularly when they are likely more efficient.
Ok so this is for JavaScript only. You have an input that you need to extract the month, date, and year from. The following is just partly an answer then on how to get the date:
<script type="text/javascript">
var myDate=new Date();
myDate.setFullYear(2011,4,16)
var a = myDate.getDate();
var t = myDate.getDay();
var r = a - t;
document.write("The date last Sunday was " + r);
</script>
So the setFullYear function sets the myDate to the date specified where the first four digits is the year, the next are is the month (0= Jan, 1= Feb.,...). The last one is the actually date. Then the above code gives you the date of the Sunday before that. I am guessing that you can add more code to get the month (use getMonth() method). Here are a few links that might be helpful
http://www.w3schools.com/js/js_obj_date.asp
http://www.w3schools.com/jsref/jsref_setFullYear.asp
http://www.w3schools.com/jsref/jsref_getMonth.asp
(You can probably find the other functions that you need)
I hope this helps a bit even though it is not a complete answer.
Yup and strtotime has been ported to JS for eg http://phpjs.org/functions/strtotime:554 here.
final code (big thanks to #Thomas & #Rob)
function lastSunday(d) {
var d = d.replace(/(^\d{4})(\d{2})(\d{2}$)/,'$1/$2/$3');
d = new Date(d);
d.setDate(d.getDate() - d.getDay());
year = d.getFullYear()+'';
month = d.getMonth()+1+'';
day = d.getDate()+'';
if ( month.length == 1 ) month = "0" + month; // Add leading zeros to month and date if required
if ( day.length == 1 ) day = "0" + day;
return year+month+day;
}

Subtracting date from an input field

I would like to have an input field with a button next to it.
On the input field I will enter a date like this:
2011-07-08
And when I hit the button it should read the time that has been entered on the input field and subtract it with 3 months and one day.
Is this possible?
Thanks in advance
Yes. First you read the date and you convert to a date object
var dateString = document.getElementById('id of your field').value,
date = new Date(dateString);
then you subtract 91 days and output the result
date.setDate(date.getDate() - 91);
alert(date.toString());
Here I assume for simplicity that you actually want 91 days and not 3 months and one day. If you want three months and one day you will do
date.setMonth(date.getMonth() - 3);
date.setDate(date.getDate() - 1);
alert(date.toString());
The Date object will take care of overflows, leap years and everything.
If you want to write it to same field, taking care of zeroes, you can do
function assureTwoDigits(number) {
if (number > 9) {
return '-' + number;
}
else {
return '-0' + number;
}
}
and change the last line to
document.getElementById('id of your field').value = date.getFullYear() + assureToDigits(date.getMonth()) + assureTwoDigits(date.getDate());
You can use Date objects (see here):
extract year, moth and day from the string (using a regular expression or splitting by '-')
buid a new Date object with that data
subtract the date interval
build the string back
The simplest way would be to split it into an array, then use a couple of if/else statements:
var date = (whatever you're pulling the date in as).split('-');
if (date[1] > 3)
date[1] = date[1] - 3;
else
date[0] = date[0] - 1;
var dateOverflow = date[1]-3;
date[1] = 12 - dateOverflow;
And then the same for the days.
Yes, it's possible and it's the most clean if you can do it without some arcane regex magic. Start by converting the date to a Date object:
// this will get you a date object from the string:
var myDate = new Date("2011-07-08");
// subtract 3 months and 1 day
myDate.setMonth(myDate.getMonth()-3);
myDate.setDay(myDate.getMonth(), myDate.getDay()-1);
// And now you have the day and it will be correct according to the number of days in a month etc
alert(myDate);

Categories

Resources