What is the process for changing a JavaScript date to the Hijri format?

Greetings! I am currently working on a web application using AngularJS/JavaScript. In my project, I have implemented a date picker and I am capturing dates from the front end. My goal is to save the selected date in the database in Hijri format. To achieve this, I followed a method for converting Gregorian date to Hijri date from this source which works perfectly when passing 1 to writeIslamicDate function. Here's an example:

var today = new Date();
writeIslamicDate(today);

However, when I pass 'today' as the input, I get undefined, NaN undefined NaN AH. Can anyone guide me on whether I need to convert the date to a specific format before passing it to writeIslamicDate? Your assistance would be highly appreciated. Thank you.

Answer №1

Just make a slight adjustment to the function provided in the link. To allow input of a date and an optional adjustment, you need to modify the function as follows:

function writeIslamicDate(adjustment) {
  ...
  var iDate = kuwaiticalendar(adjustment);

Change it to:

function writeIslamicDate(date, adjustment) {
  ...
  var iDate = kuwaiticalendar(date, adjustment);

Also, update this part:

function kuwaiticalendar(adjust) {
  var today = new Date();

to:

function kuwaiticalendar(date, adjust) {
  var today = date || new Date();

You can now call the function with either a date or without one. Below is the improved code snippet (slightly cleaned up). You may also experiment with toLocaleString along with options for language customization.

// Ensures positive modulo result
// Example: gmod(-3, 2) returns 1 instead of -1
function gmod(n, m){
  return ((n % m) + m) % m;
}

/* @param {Date}   date   - optional, defaults to current date
** @param {number} adjust - optional, days to adjust the date by
*/
function kuwaiticalendar(date, adjust) {
  var today = date ? new Date(+date) : new Date();
  if (adjust) {
    today.setDate(today.getDate() + +adjust);
  }

  // Rest of the function remains unchanged
}

// Existing function slightly modified
function writeIslamicDate(date, adjustment) {
  // Remaining code for the function writeIslamicDate not shown here
}

// Examples of using the functions...
console.log(writeIslamicDate()); 
console.log(writeIslamicDate(undefined, 1));
console.log(writeIslamicDate(new Date(2017,0,1)));
console.log(writeIslamicDate(new Date(2017,0,1), -1));

For utilizing toLocaleString, consider the following approach.

// date is optional, defaults to current date
function writeHijri(date, lang) {
  var date = date || new Date();
  lang = lang || 'en';
  var options = {
    year: 'numeric', month: 'long', day: 'numeric'
  };
  return date.toLocaleString(lang + '-u-ca-islamic', options);
}

// Examples showing the usage of writeHijri function
console.log(writeHijri());
console.log(writeHijri(new Date(2017,0,1), 'ar'));

Answer №2

Try using the moment-hijri.js library for date conversions.

Check out the Git Repo

moment('2014-11-28 16:40:00', 'YYYY-M-D HH:mm:ss').endOf('iMonth').format('iYYYY/iM/iD HH:mm:ss'); // This will output 1436/2/30 23:59:59

See a JSFIDDEL Example here

Answer №3

To easily achieve this conversion, one can utilize the browser's Intl object (learn more here). For instance, you could implement something similar to the code snippet below:

let currentDate = new Date();
let localeFormat = 'ar-SA-islamic-umalqura';
Intl.DateTimeFormat(localeFormat).format(currentDate);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I programmatically adjust the center of a Google Maps v3 map?

I have a table with 2 columns. The first column contains a div with a Google map, while the second column has a panel that changes its width after a few seconds. On the map, there is a marker placed. Issue: When I click on a button that triggers setCente ...

Error: Firebase is throwing an error stating that it cannot access the length property of an undefined property

I need help establishing a connection with Firebase. Here is the code snippet from firebase.js: import * as firebase from "firebase/compat/app"; const firebaseConfig = { apiKey: "***", authDomain: "***", projectId: &qu ...

What steps can I take to successfully run Node.js within Eclipse when the JavaScript runtime is not showing up in the preferences?

I have been encountering some difficulties with integrating Node.js into my Eclipse IDE for enterprise Java developers. I am using Eclipse Ide 2021-06 and have installed Node.js 16.3 along with npm. According to the Eclipse news, Eclipse Neon and later ve ...

Establishing a secondary setTimeout function does not trigger the execution of JQUERY and AJAX

// Custom Cart Code for Database Quantity Update $('.input-text').on('keydown ' , function(){ var tr_parent = $(this).closest("tr"); setTimeout(function () { $(tr_parent).css('opacity', '0.3'); }, 4000); var i ...

Issues with audio and video playback intermittently occurring on Sencha Touch 2

As a beginner with Sencha Touch 2, I am currently working on uploading images onto an iPad using Xcode. My app has audio playing on the home screen, and I want the video to start playing and the audio to stop when a specific tab is selected. However, the ...

What could be the issue with my JSON data stream?

Trying to set up the Fullcalendar JQuery plugin with a JSON feed has been a bit of a challenge. The example provided with the plugin works perfectly, so it seems like there might be an issue with my own feed. Here is the output from the working example JS ...

Karma and RequireJS fetching files beyond the base URL

My goal is to set up automatic testing using karma with the following file structure: /assests /css /font /img /js /collection /lib /model /plugin /spec /view test-main.js main.js /templates index.html karma.conf.js In my ...

What is the method for accessing an app from a file other than server.js?

I am dealing with two different files: file1.js const app = express(); require('./file1/config/customConfigurations').customSettings() .then((settings) => { app.locals.customSettings = settings; console.log(app.locals.customSettings) ...

Tips for setting up a typeorm entity with attention to its nullable fields

How can I assign values to typeorm entities and insert them into the database? import { PricingPatternElement } from file const Element:PricingPatternElement = { displayOrder: 10, elementName: "test", createdAt : getCurrentDate(), createdBy: &qu ...

Browser-based Javascript code execution

I've been pondering this question for a while now, and I can't seem to shake it off. I'm curious about how JavaScript is actually processed and executed in a web browser, especially during event handling scenarios. For instance, if there are ...

What exactly is the purpose of the QueryString function and how does it work

I recently took on the role of editor for a website that I did not create. One of the webpages contains a map feature, and I've been tasked with changing how the map loads initially on the webpage. As I review the JavaScript code, I'm unsure if ...

Ways to manage multiple Observables

Two Observables are being returned from different services, each providing only one value (similar to Observable.just()). In TypeScript, types play a crucial role in this context. Is there a method to determine when both Observables have been resolved (in ...

The second AJAX call is unsuccessful

I have created a dynamic ajax website that retrieves pages from the /pages folder and displays them within an ajax-container div on my index.php. Now, I am looking to implement a second ajax request that will only be triggered on certain pages. For examp ...

Development versions of npm libraries

Lately, I came across a library called react-3d-components that offers some d3 react components with basic charts. It's an impressive collection of components. However, when trying to access the source code due to incomplete documentation, I found my ...

Transform angularjs directive into angular 10

After stumbling upon this intriguing code snippet, I decided to integrate it into my angular project: 'use strict'; /** * A mesmerizing floating text animation */ angular.module('g1b.text-animation', []). directive('textAnimatio ...

Is it feasible to utilize a variable as a function within JavaScript programming?

I've been diving into the world of express.js and came across these statements. const express = require('express'); const app = express(); It's intriguing how we can call the variable "express" as a function by simply adding parenthese ...

Updating a property in React by fetching data from API and storing it in the cache

Recently, I implemented nanoid to generate unique IDs for my NBA team stat tracker app. However, upon browser refresh, the fetch function generates new IDs for each team stored in the favorites list. This causes the app to fetch data again and assign a new ...

Examining an array to identify palindromes

Is there a way to loop through an array and check if each word is a palindrome, instead of manually passing an argument for each word? If a word is a palindrome, return the word; otherwise, return 0. var myArray = ['viicc', 'cecarar', ...

A guide on integrating the MUI Timepicker with the newest 6 version using Formik

I am currently experimenting with the MUI React Timepicker component and facing an issue during integration with Formik for validation. The problem lies in the inability to bind values properly in the initialValues of the form. const [initialValues, setI ...

issues encountered when trying to integrate bootstrap.js in Django framework

My website is built using the Django templating engine with Bootstrap for design and basic JavaScript. While the CSS components from Bootstrap are working fine, I'm having trouble getting the JavaScript to work: {% load staticfiles %} <!d ...