Javascript - Multiple Arrays containing Variables - javascript

I'm new to Javascript and finding some difficulty in a task writing a program.
My task will be to write a program that will allow a user to enter their date of birth. The program then proceeds to give the corresponding Chinese Zodiac sign in an image and the number of days the user has been alive.
What will be input?
The user's year of birth (assume a valid 4 digit year will be input)
The user's month of birth (assume user will enter at least the first
three letters of a month name, but this could be longer and could
contain upper case characters, so it could be jan, Jan, january, or
January, or other month names)
The user's date (in the month) of birth (assume a valid date will be
entered)
Constants we will use
Create and appropriately name constants to store the following values:
A string containing month
abbreviations 'JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC'
The number of milliseconds in a day 1000*60*60*24
The cycle of Chinese zodiac 12
The year initialising Chinese Zodiac cycles 1924
My code so far:
var year = prompt('Enter year of birth as a 4 digit integer') // A prompt to enter the year of birth.
var month = prompt('Enter the name of the month of birth') // A prompt to enter the month of birth.
var date = prompt('Enter day of birth as an integer') // A prompt to enter the date of birth.
var month = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"]
var month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
var month = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
var month = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"]
I'm having trouble with the input of the month of birth. I'm trying to write a code to assume user will enter at least the first three letters of a month name, but this could be longer and could contain upper case characters, so it could be jan, Jan, january, or January, or other month names.
Any help will be appreciated!
George

Use .substr() to shorten their input, and .toLowerCase() to convert it to lowercase. Then match it to your array of months (the lowercase version). Here's a bit to help you get started:
var month = prompt('Enter the name of the month of birth');
// Chop everything after the first 3 characters and make it lowercase
month = month.substr(0,3).toLowerCase();
// Store your array in months, differently named than the month input
var months = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
// You can then use array.indexOf() to locate it in the array
// Not available in older browsers though
var pos = months.indexOf(month);
if (pos >= 0) {
// valid month, number is pos
}
P.S. Don't forget the ; at the end of each statement!

Combine all of your possible month strings into one array:
var year = prompt('Enter year of birth as a 4 digit integer') // A prompt to enter the year of birth.
var month = prompt('Enter the name of the month of birth') // A prompt to enter the month of birth.
var date = prompt('Enter day of birth as an integer') // A prompt to enter the date of birth.
var possibleMonths = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December",
"january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"]
Then, iterate through that one array to check to see if your user entered one of those months:
var isValidMonth = false;
for (var i = 0; i < possibleMonths.length; i++){
if (possibleMonths[i] === month){
isValidMonth = true;
break;
}
}
alert(month + " is a valid month: " + isValidMonth);

Related

change Thai month names to English using JS

I have this date 21 ต.ค. 2022 06:10 PM and i would like to change into 21 Oct 2022 06:10 PM.
This is my code:
var date = "21 ต.ค. 2022 06:10 PM";
var monthNamesThai = ["ม.ค.", "ก.พ.", "มี.ค.", "เม.ย.", "พ.ค.", "มิ.ย.", "ก.ค.", "ส.ค.", "ก.ย.", "ต.ค.", "พ.ย.", "ธ.ค."];
// var monthNamesEng = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];
var monthNamesEng = ["Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec"];
var d = new Date(date);
console.log("Change date " + d + " = " + ('0' + d.getDate()).slice(-2) + " " + monthNamesEng[d.getMonth()] + " " + d.getFullYear());
in which I get the output: Change date Invalid Date = aN undefined NaN. Is there a simple way to change the Thai month names to English without using Moment.js? Thanks in advance
var date = "21 ต.ค. 2022 06:10 PM";
var monthNamesThai = ["ม.ค.", "ก.พ.", "มี.ค.", "เม.ย.", "พ.ค.", "มิ.ย.", "ก.ค.", "ส.ค.", "ก.ย.", "ต.ค.", "พ.ย.", "ธ.ค."];
// var monthNamesEng = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];
var monthNamesEng = ["Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec"];
const thaiMonth = date.substring(date.indexOf(" ") + 1, date.indexOf(" ") + 5)
console.log(date.replace(thaiMonth, monthNamesEng[monthNamesThai.indexOf(thaiMonth)]))
make sure you Thai date always has the same format as this one, otherwise this will not work.
let date = "21 ต.ค. 2022 06:10 PM";
let monthNamesThai = ["ม.ค.", "ก.พ.", "มี.ค.", "เม.ย.", "พ.ค.", "มิ.ย.", "ก.ค.", "ส.ค.", "ก.ย.", "ต.ค.", "พ.ย.", "ธ.ค."];
let monthNamesEng = ["Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec"];
// change Thai month to english month
let englishDate = date.split(" ");
englishDate.splice(1, 1, monthNamesEng[monthNamesThai.indexOf(date.split(" ")[1])]);
englishDate = englishDate.join(" ");
let d = new Date(englishDate);
console.log("Change date " + d + " = " + ('0' + d.getDate()).slice(-2) + " " + monthNamesEng[d.getMonth()] + " " + d.getFullYear());

Is there any way to print out an specific element from an array with just its index number?

Well, I want to print out the name of the month from the .getMonth() method.
Keeping in mind that the array index starts from 0, I've made this code:
let date = new Date();
let month = date.getMonth();
month -= 1;
// As array index start from 0 but month from 1, I'm subtracting 1 from it so it too will start from 0.
let months =
[
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
]
Now I want like if it's May, I will keep the value 4, then subtract 1, which is 3.
The 3rd index in the array months is "May", but how will I ask it to check for the element with its index number?
NOTE : Please don't suggest if statements, because I don't want to use if statements for just displaying elements.
Easy: use the bracket property accessor notation:
let date = new Date
let month = date.getMonth()
let months =
[
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
]
console.log(months[month])
Arrays are little more than objects with properties named after the positive integers (ie. '0', '1', '2' etc). Because JavaScript is weakly typed you can supply a number (eg. from getMonth!) to the bracket property accessor notation, and the value will be coerced to a string, giving you the result you want.
But, as Jaromanda X points out, the better way is to use the Intl API because this will guarantee accuracy for a given user locale:
const date = new Date
console.log(new Intl.DateTimeFormat('en', { month: 'short'}).format(date))

How to get month and year from date in node js

How to get month and year data in Nodejs and query to insert into database?
var months = ["jan", "feb", "mar", "apr", "may", "jun", "july", "aug", "sep", "oct", "nov", "dec"];
var date = new Date();
var month = date.getMonth(); // returns 0 - 11
var year = date.getFullYear();
console.log(months[month]);
console.log(year);
To get the current month and year you can do the following
var date= new Date();
var month = date.getUTCMonth() + 1; //months from 1-12
var year = date.getUTCFullYear();
However i cannot answer on how to save to Database since that depends entirely on the Database and Object Modelling you are using. Can you provide more info on the Database please.
Thanks.

Javascript array output

Given the following code I need two things:
This one I know how to do, basically user inputs a number and matching month is provided in an output.
But in the same prompt if user writes a month (for eksample "Aug"), how do I return the index number?
The first part I would solve with a for loop and if/else, but how do I include also the second part with only one prompt from user?
var months = ["Not in use", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"];
var userInput = prompt("Choose a month by number or name!");
You can apply a check on the input value and return response accordingly:
let months = ["Not in use", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"];
let locator = v => Number.isNaN(Number(v)) ? months.indexOf(v) : months[v];
console.log(locator("Aug"));
console.log(locator("3"));
You can check the type of your user prompt with a if/else.
let userInput = prompt('Choose a month by number or name')
let monthNumber = parseInt(userInput)
if (monthNumber === NaN) {
// Do your stuff using userInput as a monthName
} else {
// Do your stuff using monthNumber
}
Instead of an empty first element in the array you should add 1 to the index. Next you should check if the userInput is one of the months and change it to the index of the month + 1.
let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"]
let userInput = prompt("Choose a month by number or name!");
if (months.include(userInput) {
userInput = months[userInput + 1]
}
In addition you have to turn the user input wich is a string into an integer if it is within the range between 1 and 12
let parsedInt = parseInt(userInput)
if (parsedInt >= 1 && parsedInt <= 12) {
userInput = parsedInt
}

Adding 0 before month index in javascript [duplicate]

This question already has answers here:
How can I pad a value with leading zeros?
(76 answers)
Closed 6 years ago.
I am converting the string month to an index in javascript. But the number needs to have a 2 digit month representation.
This line of code converts the index for me and adds one. This way I have the correct month.
How can I add 0 to the front of the index if the value of the index is only 1 digit? So basically if the month is any of the first 9 months how do I add a 0 in front of the number value of the month?
var expMonth = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"].indexOf(req.body.expMonth.toLowerCase()) + 1;
March would output 3. I need March to output 03
But I need October, November, December to output 10, 11, 12. Which they do as of my code now.
You can use String#slice method.
console.log(
('0' + 1).slice(-2),
('0' + 10).slice(-2),
('0' + 3).slice(-2)
)
With your code :
var expMonth = ('0' + (["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"].indexOf(req.body.expMonth.toLowerCase()) + 1)).slice(-2);

Categories

Resources