Welcome to the nuBuilder Forums!

Join our community by registering and logging in.
As a member, you'll get access to exclusive forums, resources, and content available only to registered users.

Parse DateString to get valid date object

Questions related to customising nuBuilder Forte with JavaScript or PHP.
Uzlander
Posts: 63
Joined: Sat Jul 08, 2023 10:21 am
Has thanked: 11 times
Been thanked: 3 times

Parse DateString to get valid date object

Unread post by Uzlander »

Hi community! The type of function which parses the DateString (from the date-picker, given nuDate available formats) and returns a valid Date Object (to compare/calculate/manipulate) i was in need of myself. Relatively simple implementation, still maybe others benefit form it too

Code: Select all

function parseNBDate(dateStr, dots = true, yearFirst = false) {
    if (!dateStr) return null;
    const separator = dots ? '.' : '-';
    const parts = dateStr.split(separator);
    if (parts.length !== 3) return null;
    let day, month, year;
    //
    if (yearFirst) {
        year = parseInt(parts[0], 10);
        month = parseInt(parts[1], 10);
        day = parseInt(parts[2], 10);
    } else {
        day = parseInt(parts[0], 10);
        month = parseInt(parts[1], 10);
        year = parseInt(parts[2], 10);
    }
    // 3. Handle 2-digit years if necessary
    if (year < 100) {
        year += 2000; // Assumes 21st century (e.g., 25 -> 2025)
    }
     // Validate ranges
    if (isNaN(day) || isNaN(month) || isNaN(year) || 
        day < 1 || day > 31 || 
        month < 1 || month > 12 || 
        year < 2000 || year > 9999) { return null; }
    //
    return new Date(year, month - 1, day);
}
Post Reply