JavaScript: Get lowercase Ante meridiem and Post meridiem
JavaScript Datetime: Exercise-30 with Solution
Lowercase AM/PM
Write a JavaScript function to get lowercase Ante meridiem and Post meridiem.
Sample Solution:
JavaScript Code:
// Define a JavaScript function called lower_am_pm with parameter dt (date)
function lower_am_pm(dt)
{
// Check if the hour value of the provided date is less than 12
// If true, return 'AM'; otherwise, return 'PM'
return dt.getHours() < 12 ? 'AM' : 'PM';
}
// Create a new Date object representing the current date
dt = new Date();
// Output 'AM' or 'PM' based on whether the hour value of the current date is less than 12
console.log(lower_am_pm(dt));
// Create a new Date object representing November 1, 1989
dt = new Date(1989, 10, 1);
// Output 'AM' or 'PM' based on whether the hour value of November 1, 1989, is less than 12
console.log(lower_am_pm(dt));
Output:
pm am
Explanation:
In the exercise above,
- The code defines a JavaScript function named "lower_am_pm()" with one parameter 'dt', representing a Date object.
- Inside the lower_am_pm function:
- It checks if the hour value of the provided Date object "dt" (obtained using "getHours()" method) is less than 12.
- If the hour value is less than 12, it returns 'AM', indicating the time is in the morning.
- Otherwise, it returns 'PM', indicating the time is in the afternoon or evening.
- The code then demonstrates the usage of the "lower_am_pm()" function:
- It creates a new Date object "dt" representing the current date using 'new Date()'.
- It outputs 'AM' or 'PM' based on whether the hour value of the current date is less than 12 by calling the "lower_am_pm()" function with 'dt' and logging the result to the console.
- It creates another new Date object "dt" representing November 1, 1989, using 'new Date(1989, 10, 1)'.
- It outputs 'AM' or 'PM' based on whether the hour value of November 1, 1989, is less than 12 by calling the "lower_am_pm()" function with 'dt' and logging the result to the console.
Flowchart:
Live Demo:
See the Pen JavaScript - Get lowercase Ante meridiem and Post meridiem-date-ex-30 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus.
Previous: Write a JavaScript function to get a two digit representation of a year.
Next: Write a JavaScript function to get uppercase Ante meridiem and Post meridiem.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics