Giter Club home page Giter Club logo

opensource-nepal / node-nepali-datetime Goto Github PK

View Code? Open in Web Editor NEW
62.0 6.0 18.0 774 KB

A Node project designed to support native JavaScript-like features for Nepali date and times. It includes features such as 'NepaliDate' for Nepali date support and 'dateConverter' for date conversions.

License: GNU General Public License v3.0

TypeScript 99.65% JavaScript 0.20% Shell 0.15%
ad-to-bs javascript nepal nepali nepali-date nepali-date-conversion nepali-date-converter typescript bs-to-ad

node-nepali-datetime's Introduction

nepali-datetime

npm version Github CI Downloads codecov License

nepali-datetime is a Node.js package designed to provide native JavaScript-like features for Nepali dates. It includes the 'NepaliDate' class for Nepali date support and the 'dateConverter' module for date conversion.

Examples

Here are a few examples to get you started:

import NepaliDate from 'nepali-datetime'

// Create a NepaliDate object for the current date and time
const now = new NepaliDate()
console.log(now.toString()) // Outputs: "2080-03-23 15:32:03.643"

// Create a NepaliDate object from a Nepali date string
const date1 = new NepaliDate('2079-02-15 23:11')
console.log(date1.toString()) // Outputs: "2079-02-15 23:11:00"

// Parse Nepali date string
const date2 = new NepaliDate('Baisakh 18, 2080', 'MMMM D, YYYY')
console.log(date1.toString()) // Outputs: "2080-01-18 00:00:00"

// Format a NepaliDate object
const formattedDate = now.format('YYYY-MM-DD')
console.log(formattedDate) // Outputs: "2080-03-23"

// Create a NepaliDate object from an English date
const date3 = NepaliDate.fromEnglishDate(2023, 6, 8)
console.log(englishDate.toString()) // Outputs: "2080-03-23 00:00:00"

Installation

To install nepali-datetime, you can use npm or yarn:

npm install nepali-datetime

or

yarn add nepali-datetime

Usage

NepaliDate

The NepaliDate class represents a Nepali calendar date. It provides various methods and properties to work with Nepali dates.

Creating a NepaliDate object

You can create a NepaliDate object in several ways:

  • Without any parameters: Creates a NepaliDate object for the current date and time.

    import NepaliDate from 'nepali-datetime'
    
    const now = new NepaliDate()
  • Using a Nepali date string: Parses the string as a Nepali calendar date.

    const date1 = new NepaliDate('2079-02-15')
    const date2 = new NepaliDate('2079-02-15 14:00')
  • Using a Unix timestamp (in milliseconds):

    const date2 = new NepaliDate(1654210800000)
  • Using a JavaScript Date object: Converts the JavaScript Date object to a NepaliDate object.

    const jsDate = new Date()
    const date3 = new NepaliDate(jsDate)
  • Using an existing NepaliDate object: Creates a new NepaliDate object with the same values.

    const date4 = new NepaliDate(date3)
  • Using Nepali calendar date and time parameters: Specifies the components of a Nepali calendar date.

    const date5 = new NepaliDate(year, month, date, hour, minute, second, ms)
    const date6 = new NepaliDate(2079, 2, 15, 10, 30)

Getting the Nepali date components

You can retrieve various components of a NepaliDate object using the following methods:

  • getDateObject(): Retrieves the Javascript Date object equivalent to the NepaliDate.
  • getTime(): Retrieves the Unix timestamp (in milliseconds) of the Nepali date.
  • getYear(): Retrieves the year of the Nepali date in the Nepali calendar.
  • getEnglishYear(): Retrieves the year of the Nepali date in the English calendar.
  • getMonth(): Retrieves the month of the Nepali date in the Nepali calendar.
  • getEnglishMonth(): Retrieves the month of the Nepali date in the English calendar.
  • getDate(): Retrieves the day of the month of the Nepali date in the Nepali calendar.
  • getEnglishDate(): Retrieves the day of the month of the Nepali date in the English calendar.
  • getDay(): Retrieves the day of the week represented by a numeric value.
  • getHours(): Retrieves the hour value of the Nepali date.
  • getMinutes(): Retrieves the minute value of the Nepali date.
  • getSeconds(): Retrieves the second value of the Nepali date.
  • getMilliseconds(): Retrieves the millisecond value of the Nepali date.

Setting the Nepali date components

You can set individual components of a NepaliDate object using the following methods:

  • setYear(year): Sets the year of the Nepali date.
  • setMonth(month): Sets the month of the Nepali date.
  • setDate(day): Sets the day of the month of the Nepali date.
  • setHours(hour): Sets the hour of the Nepali date.
  • setMinutes(minute): Sets the minute of the Nepali date.
  • setSeconds(second): Sets the second of the Nepali date.
  • setMilliseconds(ms): Sets the millisecond of the Nepali date.
  • setTime(time): Sets the Nepali date and time values using a Unix timestamp.

Formatting the Nepali date

You can format a NepaliDate object as a string using the format() and formatNepali() methods.

  • format(formatStr): Returns a string representation (in English) of the NepaliDate object in the specified format.
  • formatNepali(formatStr): Returns a string representation in the Nepali (Devanagari) script of the NepaliDate object in the specified format.
const now = new NepaliDate(2079, 5, 3, 16, 14)
console.log(now.format('YYYY-MM-DD hh:mm A')) // Outputs: 2079-06-03 04:14 PM

The date formatting will follow the format codes mentioned below, which are similar to the date formats used in day.js.

Format Token Description Example
YYYY 4-digit year 2023
YY 2-digit year 23
MMMM Full month name Baisakh
MMM Abbreviated month name Bai
MM 2-digit month 01-12
M Month number, beginning at 1 1-12
DD 2-digit day of the month 01-31
D Day of the month 1-31
dddd Full day of the week Monday
ddd Abbreviated day of the week Mon
d Day of the week, with Sunday as 0 0-6
HH 2-digit hour (24-hour format) 00-23
H Hour (24-hour format) 0-23
hh 2-digit hour (12-hour format) 01-12
h Hour (12-hour format) 1-12
mm 2-digit minutes 00-59
m Minutes 0-59
ss 2-digit seconds 00-59
s Seconds 0-59
SSS 3-digit milliseconds 000-999
A Uppercase AM/PM AM or PM
a Lowercase am/pm am or pm

Any other character will be printed as it is. If you need to print the special characters (YMDmd), please enclose them within square brackets. Example: .format("[YMDmd]")

For the list of month names and their abbreviations, you can refer to the table below.

Value of Month Abbreviation Full Name
0 Bai Baisakh
1 Jes Jestha
2 Asa Asar
3 Shr Shrawan
4 Bhd Bhadra
5 Asw Aswin
6 Kar Kartik
7 Man Mangsir
8 Pou Poush
9 Mag Magh
10 Fal Falgun
11 Cha Chaitra

Converting to JavaScript Date object

You can get the equivalent JavaScript Date object of a NepaliDate object using the getDateObject() method.

const now = new NepaliDate(2079, 5, 3)
console.log(now.getDateObject()) // Date 2022-09-18T18:15:00.000Z

Creating a NepaliDate object from an English date

You can create a NepaliDate object from an English calendar date using the fromEnglishDate method.

const date = NepaliDate.fromEnglishDate(2023, 6, 8)
console.log(date.toString()) // Outputs: "2080-03-23 00:00:00"

dateConverter

The dateConverter module provides functions for converting dates between the Nepali and English calendars.

  • englishToNepali(year, month, day): Converts an English calendar date to a Nepali calendar date. Returns an array [yearNp, monthNp, dayNp] representing the Nepali date.
  • nepaliToEnglish(year, month, day): Converts a Nepali calendar date to an English calendar date. Returns an array [yearEn, monthEn, dayEn] representing the English date.
import dateConverter from 'nepali-datetime/dateConverter'

// english to nepali date conversion
const [npYear, npMonth, npDay] = dateConverter.englishToNepali(2023, 5, 27)

// nepali to english date conversion
const [enYear, enMonth, enDay] = dateConverter.nepaliToEnglish(2080, 2, 15)

Acknowledgements

This project was inspired by nepali-date. We would like to express our gratitude to their team for their excellent work and ideas, which served as a motivation for this project.

Contribution

We appreciate feedback and contribution to this package. To get started please see our contribution guide.

node-nepali-datetime's People

Contributors

aj3sh avatar binodnepali avatar bitchangerofficial avatar codesterlalit avatar dependabot[bot] avatar github-actions[bot] avatar mhrjaniiz avatar n1rjal avatar rubiin avatar shakyaprasen avatar subashcs avatar sugat009 avatar syaau avatar tilakbasyal avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

node-nepali-datetime's Issues

Date invalid bug even if date is valid

Describe the bug
i was using like this it is giving me date invalid exception
dateConverter.englishToNepali(2023, 12, 6)

To Reproduce
use english to nepali converter and use december(12) as second parameter in englishToNepali method .

Expected behavior
It should have shown the correct nepali date for those english dates.

Environment

  • npm/node version:20
  • Package version:1.2.0
  • Operating system: windows 10
  • Any other relevant information about your environment.

Additional context
Please provide any additional context or information that may be helpful in understanding and resolving the issue. This can include:

  • Error stack trace
  • Error messages
  • Uncaught DateOutOfRangeError: Date out of range
    at Object.D [as englishToNepali] (nepali-datetime.008218f8.mjs:1:4950)
    at ComplaintCard (ComplaintCard.jsx:15:28)
    at renderWithHooks (react-dom.development.js:16305:18)
    at mountIndeterminateComponent (react-dom.development.js:20074:13)
    at beginWork (react-dom.development.js:21587:16)
    at beginWork$1 (react-dom.development.js:27426:14)
    at performUnitOfWork (react-dom.development.js:26557:12)
    at workLoopSync (react-dom.development.js:26466:5)
    at renderRootSync (react-dom.development.js:26434:7)
    at recoverFromConcurrentError (react-dom.development.js:25850:20)
  • Log files
  • Screenshots
  • Any other relevant details related to the issue.

Refactor Current Formatting Method for Improved Performance and Readability

The current formatting code in format.ts is not easily readable and poses challenges for enhancement. The reason behind this issue is the utilization of a legacy formatting code from the nepali-date repository. While some parts of the code have already been refactored, further improvements are necessary to enhance its performance.

Furthermore, for escaping characters, let's replace the double quote " with brackets [] to achieve consistency with moment.js and day.js.

Add prettier check on CI

Problem:
Currently, we have a Prettier check implemented solely as a pre-commit hook. While this is a valuable step in maintaining code quality, it's not sufficient as it can be bypassed. Developers can inadvertently or deliberately skip this step, potentially leading to inconsistent code formatting.

Proposal:
We should enhance our code formatting enforcement by adding a Prettier check to our GitHub Actions workflow. This will ensure that code formatting is consistently applied before changes are merged into our codebase.

Add support for devanagari date string while parsing

This feature allows us to take input from Devanagari strings such as "२०७८-०१-१८" into the NepaliDate object. The current parse module should handle the Devanagari string so that the NepaliDate object can be initialized from such class.

const nepaliDate = new NepaliDate("२०७८-०१-१८")

The steps for parsing are like below:

  1. The input (can be both English or Devanagari string)
  2. Translate the Devanagari date strings to English strings. Translation includes numbers, months, and months abbrs.
  3. Use the translated English string for parsing.

Add standard version

Use Case
Automate versioning and CHANGELOG generation to remove manual effort for changelog writing.

Proposed Solution
I see in the repo most of the time commit message is following conventional commit message. Maybe, we can use standard version to automate versioning and changelog generation.

Alternative Considered

Dependencies

Additional context

Implement pre-commit hooks

Pre-commit hooks serve as a preventive measure to ensure that certain checks, validations, or tasks are performed before the code is committed to the repository. The purpose of implementing a pre-commit hook is to enforce code quality, maintain project standards, and catch potential issues early on, thereby reducing the chances of introducing bugs or breaking the build.

Refactor output formatting, change to % formats

The current output formatting uses a format that is difficult to understand. For making the output formatting similar to py-nepali and go-nepali projects, let's change the formatting to % formats.

Support Hour, minute, seconds, miliseconds formatting from NepaliDate's format method

The current feature of the NepaliDate class only supports formatting for year, months, and days. However, it partially supports hours, minutes, and seconds without the formatting feature. To address this, let's extend the existing format feature to support hours, minutes, seconds, and other related formats.

It's important to note that there are conflicts with some formats due to Nepali Unicode support. For example, 'm' is currently used as the format for months in Nepali Unicode, but it should represent minutes in time formatting. To resolve this conflict, we'll create a new method called formatNepali() specifically for Nepali Unicode support. We'll also remove support for Nepali Unicode from the existing format() method.

The new date formats will follow the format codes used in moment.js date formats. Here are the updated formats:

  1. Year:

    • YYYY: 4-digit year (e.g., 2023)
    • YY: 2-digit year (e.g., 23)
  2. Month:

    • MMMM: Full month name (e.g., January)
    • MMM: Abbreviated month name (e.g., Jan)
    • MM: 2-digit month (e.g., 01)
    • M: Month without leading zeros (e.g., 1)
  3. Day:

    • DD: 2-digit day of the month (e.g., 01)
    • D: Day of the month without leading zeros (e.g., 1)
    • dddd: Full day of the week (e.g., Sunday)
    • ddd: Abbreviated day of the week (e.g., Sun)
  4. Hours:

    • HH: 24-hour format with leading zeros (e.g., 00, 01, 23)
    • H: 24-hour format without leading zeros (e.g., 0, 1, 23)
    • hh: 12-hour format with leading zeros (e.g., 01, 02, 12)
    • h: 12-hour format without leading zeros (e.g., 1, 2, 12)
  5. Minutes:

    • mm: Minutes with leading zeros (e.g., 00, 01, 59)
    • m: Minutes without leading zeros (e.g., 0, 1, 59)
  6. Seconds:

    • ss: Seconds with leading zeros (e.g., 00, 01, 59)
    • s: Seconds without leading zeros (e.g., 0, 1, 59)
  7. AM/PM:

    • A: Uppercase AM/PM indicator (e.g., AM, PM)
    • a: Lowercase AM/PM indicator (e.g., am, pm)

To implement these changes, you can follow these steps:

  1. Create a new method named formatNepali() within the NepaliDate class to support Nepali Unicode formatting.
  2. Update the existing format() method to remove support for Nepali Unicode and modify the formatting options to align with the new formats.
  3. Implement the new formats for time and weekday.
  4. Write tests to ensure the new formatting methods work correctly.

By making these changes, you should be able to format Nepali dates with additional options for hours, minutes, seconds, and more.

Add timezone support

Problem Statement

The current implementation of NepaliDate doesn't support time and timezone. Running this package in different timezone machines gets affected.

Propose Solution

Implement "Asia/Kathmandu" timezone support

Change tooling for build

Use Case
Please describe the specific use case or scenario where this feature would be beneficial.
Right now , we are using rollup directly for building the file , I suggest we should go for something like https://github.com/unjs/unbuild that uses rollup and provides a level of abstraction

Proposed Solution
This will greatly improve DX for maintainers and collaboraters.
Compare the setup file for plain rollup (~38lines)

vs

Setup file for unbuild (~17lines)

Also with unbuild you don't need to install external rollup plugins for compilations as most cases are handled by default.

Alternative Considered
https://github.com/egoist/tsup is also a great alternative

Dependencies
If this feature has any dependencies or requirements, please list them here.

Additional context
Add any other context or screenshots about the feature request here.

Update Community standards

Following Community Standards include:

  • Github Project description
  • Readme document
  • Code of Conduct
  • Contributing document
  • License
  • Security policy
  • Issues templates
  • PR template

Refactor NepaliDate constructor

The current implementation of the NepaliDate constructor lacks clarity and is difficult to comprehend. Let's proceed with refactoring it to improve its readability and understandability.

Integrate coverage and its report using codecov

We have run the test from CI using GitHub actions. This makes sure that all the tests are passing before. However, the question is are the test cases fully covered? So coverage report is important. The used dev library 'jest' has a feature for generating coverage reports.

Therefore, let's use the coverage and publish it through codecov. Also, add the coverage percentage on README.md.

Inconsistent months data for date conversion

We have noticed inconsistencies in the monthly data across Hamro Patro and Nepali Patro, starting from the year 2081. This inconsistency was initially highlighted in the go-nepali project (opensource-nepal/go-nepali#15). The issue was addressed in this project through PR #79. However, this PR only fixes the data for the year 2081.

After a thorough examination, here's what I discovered:

  • Hamropatro has incorrect data for the year 2087, with 367 days in a year.
  • The data pattern of the Baishakh from Nepali Patro appears to follow a specific pattern and is likely to provide accurate information.

Here are the data from different sources:

[Year]
[Current Data]
[Hamro Patro Data]
[Nepali Patro Data]

[2082]
30 32 31 32 31 30 30 30 29 30 30 30
30 32 31 32 31 30 30 30 29 30 30 30
31 31 31 32 31 31 30 29 30 29 30 30

[2083]
31 31 32 31 31 30 30 30 29 30 30 30
31 31 32 31 31 30 30 30 29 30 30 30
31 31 32 31 31 31 30 29 30 29 30 30

[2084]
31 31 32 31 31 30 30 30 29 30 30 30
31 31 32 31 31 30 30 30 29 30 30 30
31 32 31 32 31 30 30 30 29 29 30 31

[2085]
31 32 31 32 30 31 30 30 29 30 30 30
31 32 31 32 30 31 30 30 29 30 30 30
30 32 31 32 31 30 30 30 29 30 29 31

[2086]
30 32 31 32 31 30 30 30 29 30 30 30
30 32 31 32 31 30 30 30 29 30 30 30
31 31 32 31 31 31 30 29 30 29 30 30

[2087]
31 31 32 31 31 31 30 30 29 30 30 30
31 31 32 31 31 31 30 30 30 30 30 30
31 31 32 32 31 30 30 29 30 29 30 30

[2088]
30 31 32 32 30 31 30 30 29 30 30 30
30 31 32 32 30 31 30 30 29 30 30 30
31 32 31 32 31 30 30 30 29 29 30 31

Possible solutions

  1. Align with one of the data sources.
  2. Wait for the updated 2082 data and compare which source had the correct data.
  3. ...

Add time support

Problem Statement

The current implementation of NepaliDate doesn't support time.

Propose Solution

The time should be implemented on NepaliDate class or a new class NepaliDatetime

Add support for initializing with Nepal Timezone's date parameters

Let's say I am in a different timezone, for instance, America/Chicago, and I want to initialize a Nepali Date time object from the parameters "2018-03-12 13:00". If I try new Date(2018, 2, 12, 13, 0) it will create a date object of Chicago timezone. If I was in the Nepal timezone, it wouldn't be a problem.

Let's create a new static function that initializes NepaliDate from the date params ignoring the timezone.

Example:

NepaliDate.fromEnglishDate(2018, 2, 12, 13, 0)

Create a dateConverter module

Problem Statement:
The current implementation of NepaliDate contains all the logic within the class, including formatting, parsing, and date conversion. This results in confusion, decreased readability, and potential errors.

Proposed Solution:
Let's create a separate module dedicated to date conversion, specifically responsible only for date conversion.

Additional Info:
The current implementation doesn't support the Nepali date 2000/01/01

Github Actions implementation for release

Implement Github actions for triggering the release process (eg. building code, compiling docs, publishing package, etc). This Github action should be dependent on the Github release.

format token for 12 hour format time is incorrect

Describe the bug
Once date is initialised and try to format the date using 12 hour format token, the output is incorrect

To Reproduce
const now = new NepaliDateTime(2079, 5, 3, 12, 15)
console.log(now.format('YYYY-MM-DD hh:mm A'))
// Output: 2079-06-03 12:15 AM

Expected behavior
However, output should be 2079-06-03 12:15 PM

Environment

  • npm/node version: v18.14.2
  • Package version: ^1.1.1
  • Operating system:
  • Any other relevant information about your environment.

Additional context
Please provide any additional context or information that may be helpful in understanding and resolving the issue. This can include:

  • Error stack trace
  • Error messages
  • Log files
  • Screenshots
  • Any other relevant details related to the issue.

2024.6.14-2024.7.15;2025.3.14-2025.4.13 dates are converted to Nepal dates incorrectly

Describe the bug
A clear and concise description of what the bug is.
2024.6.14-2024.7.15;2025.3.14-2025.4.13 dates are converted to Nepal dates incorrectly;
To Reproduce
Please provide the steps to reproduce the issue. Include code snippets or specific examples if applicable.

Expected behavior
Please provide a clear and concise description of your expected outcome.
Just use the date in the above issue to reproduce it using the NepaliDate.fromEnglishDate() method
Environment

  • npm/node version:
  • Package version:v12.22.11
  • Operating system:vue
  • Any other relevant information about your environment.

Additional context
Please provide any additional context or information that may be helpful in understanding and resolving the issue. This can include:

  • Error stack trace
  • Error messages
  • Log files
  • Screenshots
  • Any other relevant details related to the issue.

Add feature for formatting and parsing english date

JavaScript lacks an easy way to format/parse Date objects. Let's create a utility from NepaliDate.

The APIs would look like the following:

  • nepaliDateObj.formatEnglishDate("YYYY-MM-DD")
  • nepaliDate = NepaliDate.parseEnglishDate("2018-12-48", "YYYY-MM-DD")

Use Cases

  • Assists in initializing NepaliDate from an English date string.
  • Facilitates obtaining the English date of a NepaliDate in a specific format.

Typescript could not find module declaration to resolve typing.

Describe the bug
When I try to import package using es module system in ts project. I am getting type declaration module not found and I have attached screenshot.

To Reproduce
Just import package.
import NepaliDate from 'nepali-datetime'

Expected behavior
There should not error and type completion should be working

Environment

  • npm/node version: 9.5.0/18.14.2
  • Package version: ^1.1.0
  • Operating system: macOS ventura 13.5.1
  • Any other relevant information about your environment.

Additional context
Please provide any additional context or information that may be helpful in understanding and resolving the issue. This can include:

  • Screenshots
error

Create a methods for fetching English year, month, date (nepali timezone)

Currently, we can fetch English year, month, and date by using the following ways:

const nepaliDateObj = NepaliDate(...)
const englishDateObj = nepaliDate.getEnglishDate()
const year = englishDateObj.getFullYear()
const month = englishDateObj.getMonth()
const date = englishDateObj.getDate()

But the .getEnglishDate() returns the date object with the current system timezone, which may not be Nepal's timezone. So the year, month, and date wouldn't be the same as in Nepal's.

So let's create new methods for getting English year, month, and date.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.