JavaScript datetime object helper functions
A collection of helper functions for using JavaScript datetime object.
var getCurrentDate = function(){
// Get the current date
var today = new Date();
// Extract day
var day = today.getDate();
// Add leading zero if day is a single digit
if(day < 10){
day = '0' + day;
}
// Extract month
var month = today.getMonth() + 1; // Months are zero-based
// Add leading zero if month is a single digit
if(month < 10){
month = '0' + month;
}
// Format the date as DD.MM.YYYY
var date = day + '.' + month + '.' + today.getFullYear();
// Return the formatted date
return date;
};
// Example usage
var currentDate = getCurrentDate();
console.log("Current Date: " + currentDate); // Current Date: 12.11.2019
var isValidDateObject = function(dt) {
// Make sure the input is a valid Date object
if (!(dt instanceof Date) || isNaN(dt)) {
return false;
}
// If the date is valid, return true
return true;
};
// Example usage
var validDate = new Date(); // a valid Date object
var invalidDate = "not a date"; // not a valid Date object
// Check if the values are valid Date objects
console.log("Is validDate a valid Date object? " + isValidDateObject(validDate)); // Should print: true
console.log("Is invalidDate a valid Date object? " + isValidDateObject(invalidDate)); // Should print: false
var getDateObjectFromDateString = function(dateString) {
// Extract components
var dateComponents = dateString.split(".");
var day = parseInt(dateComponents[0], 10);
var month = parseInt(dateComponents[1], 10) - 1; // Months are zero-based
var year = parseInt(dateComponents[2], 10);
// Create Date object
var dateObject = new Date(year, month, day);
// Check if the date object is valid
if (!isValidDateObject(dateObject)) {
// If the date is invalid, return false
return false;
}
// If the date is valid, return the Date object
return dateObject;
};
// Example usage
var dateString = "12.11.2019";
var dateObject = getDateObjectFromDateString(dateString);
if (dateObject) {
console.log("Date object created:", dateObject);
} else {
console.log("Invalid date string");
}
var subtractSecondsFromDate = function(dt, secondsToSubtract) {
// Make sure the input is a valid Date object
if (!isValidDateObject(dt)) {
return false;
}
// Calculate the new time in milliseconds
var newTime = date.getTime() - secondsToSubtract * 1000;
// Create a new Date object with the adjusted time
var newDate = new Date(newTime);
return newDate;
};
// Example usage: Calculate the date 1 year ago
var currentDate = new Date();
var secondsInOneYear = 365 * 24 * 60 * 60; // Assuming a non-leap year
var oneYearAgo = subtractSecondsFromDate(currentDate, secondsInOneYear);
console.log("Current Date:", currentDate);
console.log("Date 1 year ago:", oneYearAgo);
var formatDateStr = function(str){
// Trim leading and trailing whitespaces
var dt = str.trim();
// Split the date string into an array of components
var sp = dt.split('.');
// Reformat the date string to "YYYY-MM-DDTHH:mm:ss"
return sp[2] + '-' + sp[1] + '-' + sp[0] + 'T00:00:00';
};
// Example usage
var inputDate = "12.11.2019";
var formattedDate = formatDateStr(inputDate);
console.log("Original Date String:", inputDate); // 12.11.2019
console.log("Formatted Date String:", formattedDate); // 2019-11-12T00:00:00
var daysBetween = function(date1, date2) {
try {
// Convert the dates to milliseconds.
var ms1 = date1.getTime();
var ms2 = date2.getTime();
// Calculate the difference in milliseconds.
var diff = ms2 - ms1;
// Divide the difference by the number of milliseconds in a day.
var days = diff / (1000 * 60 * 60 * 24);
// Return the absolute value of the difference in days.
return Math.floor(days);
} catch (errMsg) {
// Handle any potential errors (though not clear what error might occur here).
}
// Return 0 if an error occurs or if there is no difference in days.
return 0;
};
// Example usage
var startDate = new Date("2019-01-01");
var endDate = new Date(); // Current date
var daysDifference = daysBetween(startDate, endDate);
console.log("Start Date:", startDate.toISOString()); // Start Date: 2019-01-01T00:00:00.000Z
console.log("End Date:", endDate.toISOString()); // End Date: 2019-11-13T13:10:12.574Z
console.log("Days Between:", daysDifference); // Days Between: 316