Snippets Collections
/**
 * Format a given date object to YYYY-MM-DD format.
 * 
 * @param {Date} date The date object to be formatted.
 * @returns {string} The formatted date in YYYY-MM-DD format.
 */
function formatDateToYYYYMMDD(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const formattedDate = `${year}-${month}-${day}`;
    return formattedDate;
}
const formatDate = (date) =>
  new Intl.DateTimeFormat("en", {
    day: "numeric",
    month: "long",
    year: "numeric",
    weekday: "long",
  }).format(new Date(date));


  export default formatDate
const dateUtils = {
    language: 'es',

    dateToDay: function(date) {
        return new Date( (new Date(date)).setHours(0, 0, 0, 0) );
    },
    dateToYMD: function date(date) {
        return new Date( (new Date(date)).setHours(0, 0, 0, 0) )
            .toISOString().split('T')[0];
    },

    today: function() {
        return new Date( (new Date()).setHours(0, 0, 0, 0) );
    },
    todayYMD: function() {
        return new Date( (new Date()).setHours(0, 0, 0, 0) )
            .toISOString().split('T')[0];
    },

    ymdToDate: function(ymd) {
        return ymd.length === 10 ?
            new Date(new Date(ymd).setHours(0, 0, 0, 0)) :
            new Date(ymd);
    },

    is_ymd: function(value) {
        if(value === null)
            return false;
        if(typeof value !== 'string')
            return false;
        if(!isNaN(value))
            return false;
        if(value.length < 10 || value.length > 27)
            return false;
        const regex =
           /^\d\d\d\d[-.\\\/_](0[1-9]|1[0-2])[-.\\\/_](0[1-9]|[1-2][0-9]|[0|1])($|([ T]([0-1]\d|2[0-4]):[0-5]\d:[0-5]\d))/gm;
        return value.match(regex) !== null;
    },

    /**
     * Formats a date according to the given format string in PHP style.
     * If no format string is provided, it defaults to "d/M/y".
     *
     * @param {Date|string|number} inputDate - The date to be formatted. Can be a Date object, a date string, or a timestamp.
     * @param {string} [formatPhpStyle="d/M/y"] - The format string to be used for formatting the date. Defaults to "d/M/y"
     *  https://www.php.net/manual/en/datetime.format.php.
     * @returns {string} - The formatted date string.
     * @throws {Error} - If an error occurs during the formatting process.
     */
    format: function(inputDate, formatPhpStyle = "d/M/y")  {
        if(this.shortMonth.length === 0)
            this.setLanguage();
        if(inputDate === null)
            return "";
        try {
            function padZero(value) {return value < 10  ? `0${value}` : `${value}`;}
            let date;
            if(inputDate instanceof Date)
                date = inputDate;
            else if(typeof inputDate === 'object')
                return "[object]";
            else if(isNaN(inputDate))
                date = this.is_ymd(inputDate) ?
                    new Date(`${inputDate}T00:00:00`) : new Date(inputDate);
            else
                date = new Date(inputDate);

            const parts = {
                d: padZero(date.getDate()),
                j: date.getDate(),
                D: this.shortDay[date.getDay()],
                l: this.longDay[date.getDay()],
                w: date.getDay(),

                m: padZero(date.getMonth() + 1),
                n: date.getMonth() + 1,
                M: this.shortMonth[date.getMonth()],
                F: this.longMonth[date.getMonth()],

                Y: date.getFullYear(),
                y: date.getFullYear().toString().slice(-2),

                H: padZero(date.getHours()),
                G: date.getHours(),
                h: padZero(date.getHours() > 12 ? date.getHours() - 12 : date.getHours()),
                g: date.getHours() > 12 ? date.getHours() - 12 : date.getHours(),
                i: padZero(date.getMinutes()),
                s: padZero(date.getSeconds()),

                a: date.getHours() < 12 ? 'am' : 'pm',
                A: date.getHours() < 12 ? 'AM' : 'PM',
            };

            let skip = false;
            let ret = [];
            for(let i = 0, len = formatPhpStyle.length; i < len; ++i) {
                let c = formatPhpStyle[i];
                if(c === "\\") {
                    skip = true;
                    continue;
                }
                if(skip) {
                    skip = false;
                    ret.push(c);
                    continue;
                }
                ret.push(parts.hasOwnProperty(c) ? parts[c] : c);
            }
            return ret.join("");
        } catch(error) {
            console.log("ERROR: fmt.date arguments:", arguments);
            console.log("       fmt.date error:", error);
            return inputDate;
        }
    },
    longMonth: [],
    shortMonth: [],
    longDay: [],
    shortDay: [],
    setLanguage(lang) {
        if(typeof lang === 'undefined')
            lang = this.language;
        switch(lang.toLowerCase()) {
            case 'en':
                this.longMonth = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September',
                    'October', 'November', 'December'];
                this.shortMonth = ['Jan', 'Feb', 'Mar', 'Apr', 'May',  'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
                this.longDay = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
                this.shortDay = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'];
                return;
            case 'es':
            default:
                this.longMonth = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto',
                    'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];
                this.shortMonth = ['Ene', 'Feb', 'Mar', 'Abr', 'May',  'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'];
                this.longDay = ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'];
                this.shortDay = ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sa'];
                return;
        }
    },
};
Earliest Date

= #date(Date.Year(List.Min(Source[OrderDate])),1,1)

Latest Date

= #date(Date.Year(List.Max(Source[RequiredDate])),12,31)

(Dynamic) Calendar
let
    Source = {Number.From(pmEarliestDate)..Number.From(pmLatestDate)},
    #"Converted to Table" = Table.FromList(Source, Splitter.SplitByNothing(), null, null, ExtraValues.Error),
    #"Renamed Columns" = Table.RenameColumns(#"Converted to Table",{{"Column1", "Date"}}),
    #"Changed Type" = Table.TransformColumnTypes(#"Renamed Columns",{{"Date", type date}})
in
    #"Changed Type"
    func timeAgoDisplay(previousTime : Int) -> String {
        
        let cTime = Int(NSDate().timeIntervalSince1970)
        let pTime = previousTime/1000
        
        let secondsAgo = cTime - pTime
        
        let minute = 60
        let hour = 60 * minute
        let day = 24 * hour
        let week = 7 * day
        let month = day * 30
        let year = month * 12
        
        
        
        if secondsAgo < minute {
            var txt = ""
            if secondsAgo == 1 {
                txt = "second ago"
            } else {
                txt = "seconds ago"
            }
            return "\(secondsAgo) \(txt)"
        } else if secondsAgo < hour {
            var txt = ""
            let minutes = secondsAgo / minute
            if minutes == 1 {
                txt = "minute ago"
            } else {
                txt = "minutes ago"
            }
            return "\(minutes) \(txt)"
        } else if secondsAgo < day {
            var txt = ""
            let hours = secondsAgo / hour
            if hours == 1 {
                txt = "hour ago"
            } else {
                txt = "hours ago"
            }
            return "\(hours) \(txt)"
        } else if secondsAgo < week {
            var txt = ""
            let days = secondsAgo / day
            if days == 1 {
                txt = "day ago"
            } else {
                txt = "days ago"
            }
            return "\(days) \(txt)"
        } else if secondsAgo < month {
            var txt = ""
            let weeks = secondsAgo / week
            if weeks == 1 {
                txt = "week ago"
            } else {
                txt = "weeks ago"
            }
            return "\(weeks) \(txt)"
        } else if secondsAgo < year {
            var txt = ""
            let months = secondsAgo / month
            if months == 1 {
                txt = "month ago"
            } else {
                txt = "months ago"
            }
            return "\(months) \(txt)"
        } else {
            var txt = ""
            let years = secondsAgo / year
            if years == 1 {
                txt = "year ago"
            } else {
                txt = "years ago"
            }
            return "\(years) \(txt)"
        }
    }
    let datePicker =  UIDatePicker()
    let toolBar = UIToolbar()
    
    var pickedDate = ""
    var dobTimeStamp = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
      
        createDatePicker()
    }


// MARK: - Date Picker

extension SignUpViewController {
    
    func createDatePicker() {
        toolBar.sizeToFit()
     //   toolBar.layer.frame.size = CGSize(width: 414, height: 500)
        
        let doneBtn = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(donePressed))
        toolBar.setItems([doneBtn], animated: true)
        datePicker.preferredDatePickerStyle = .wheels
        datePicker.datePickerMode = .date
    }
    
    @objc func donePressed() {
        let dateFormatter: DateFormatter = DateFormatter()
        dateFormatter.dateFormat = "dd MMM,yyyy"
        pickedDate = dateFormatter.string(from: datePicker.date)
        print("picked Date : ", pickedDate)
        let myTimeStamp = Int(self.datePicker.date.timeIntervalSince1970)
        dobTimeStamp = String(myTimeStamp * 1000)
        self.view.endEditing(true)
    }
}

// MARK: Text Field

extension SignUpViewController: UITextFieldDelegate {
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        
        if textField.tag == 4 {
            textField.inputAccessoryView = toolBar
            textField.inputView = datePicker
            datePicker.maximumDate = Date()
        }
    }
}
#include<iostream>
using namespace std;
class DATE{
    int day;
    int month;
    int year;
    public:
    DATE(){}
    DATE(char*);
    int operator-(DATE);
    DATE operator+(int);
    bool operator<(DATE);
    friend ostream& operator<<(ostream &,DATE&);
    ~DATE();
};
int main(){

    cout<<"Enter the first date in dd/mm/yyyy format: ";
    char input[20];
    cin>>input;
    DATE d1(input);
    cout<<d1<<endl;
    cout<<"Enter the second date in dd/mm/yyyy format: ";
    cin>>input;
    DATE d2(input);
    cout<<d2<<endl;
    int num_days = d2-d1;
    
    cout<<"Number of days in between is: "<<num_days<<endl;
    cout<<"Enter the number of days\n";
    int num;
    cin>>num;
    DATE d3 = d1 + num;
    cout<<d1<<" + "<<num<<" = "<<d3;
    return 0;
}
int my_stoi(char *input,int start,int len){
    int output =0;
    for(int i=start;i<start+len;i++){
        output = output*10 + input[i]-'0';
    }
    return output;
}
DATE::DATE(char *input){
    day = my_stoi(input,0,2);
    month = my_stoi(input,3,2);
    year = my_stoi(input,6,4);
}
inline bool is_leap_year(int yy){
    if(yy%400==0) return 0;
    return yy%4 ? 0: 1;
}
inline int days_in_year(int yy){
    return is_leap_year(yy) ? 366 : 365;
}
int days_in_month(int mo,int yy){
    switch(mo){
        case 1:case 3:case 5: case 7: case 8: case 10: case 12:
            return 31;
        case 4: case 6: case 9: case 11:
            return 30;
        case 2: 
            if(is_leap_year(yy)) return 29;
            else return 28;
    }
    return -1;
}
bool DATE::operator<(DATE d2){
    if(year<d2.year) return true;
    else if(year>d2.year) return false;
    if(month<d2.month) return true;
    else if(month>d2.month) return false;
    return day<d2.day;
}
int DATE::operator-(DATE d2){
    if(*this<d2) return d2-*this;

    int prefix_days_d1 =0;
    for(int i=1;i<month;i++) prefix_days_d1 += days_in_month(i,year);
    prefix_days_d1 += day;

    int suffix_days_d2=0;
    suffix_days_d2 += days_in_month(d2.month,d2.year)-d2.day;
    for(int i = d2.month+1;i<=12;i++) suffix_days_d2 += days_in_month(i,d2.year);

    int difference = suffix_days_d2 + prefix_days_d1;

    for(int i = d2.year+1 ; i<year ; i++){
        difference += days_in_year(i);
    }
    if(year==d2.year) difference -= days_in_year(year);   // overlap
    return difference;
}
ostream& operator<<(ostream &print,DATE &obj){
    if(obj.day/10 ==0) print<<"0";
    print<<obj.day;
    print<<"/";
    if(obj.month/10 ==0) print<<"0";
    print<<obj.month<<"/";
    print<<obj.year;
    return print;
}
DATE DATE::operator+(int add_days){
    DATE output;
    int dd = day;
    int mm = month;
    int yy = year;
    int current_days = days_in_month(mm,yy) - dd;
    if(add_days > current_days){  
                                    // rounding up the month
        add_days-=current_days;
        mm++;
        if(mm==13) {
            mm=1;
            yy++;
        }
    }
    else{
        dd +=add_days;
        add_days=0;
    }
    while(days_in_month(mm,yy)<add_days){
                                        // rounding up the year
        add_days-=days_in_month(mm,yy);
        mm++;
        if(mm==13) {
            mm=1;
            yy++;
            break;
        }
    }
    while(days_in_year(yy)<add_days){   //locating to the year
        add_days-=days_in_year(yy);
        yy++;
    }
    while(days_in_month(mm,yy)<add_days){ // locating to the month
        add_days-=days_in_month(mm,yy);
        mm++;
    }
    if(add_days!=0) dd = add_days;  // locating to the date
    output.day = dd;
    output.month = mm;
    output.year = yy;

    return output;
}
DATE::~DATE(){
    
}
  private String getFormatedDate(long time){
        simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
        String formatedDate = simpleDateFormat.format(time);
        return formatedDate;
    }
let now = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "LLLL"
let nameOfMonth = dateFormatter.string(from: now)
const today = new Date()
const oneMonthAgo = new Date(today.getFullYear(), today.getMonth() - 1, today.getDate())
func isDayEnded(recent: Date, previous: Date) -> Bool {
    let day:Int = Calendar.current.dateComponents([.day], from: previous, to: recent).day ?? 0
    if day >= 1 {
        return true
    } else {
        return false
    }
}
let previous = NSDate(timeIntervalSince1970: 1645601459)
let recent = NSDate(timeIntervalSince1970:   1648020659)
let dayEnded = isDayEnded(recent: recent as Date, previous: previous as Date)
print("Day = \(dayEnded)")
    func getDateTime(_ timeStamp : String,_ format: String) -> String {
        var t1 = Int(timeStamp) ?? 1
         t1 = t1/1000
        let date = NSDate(timeIntervalSince1970: TimeInterval(t1))
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = format
        let dateString = dateFormatter.string(from: date as Date)
        print("Date = \(dateString)")
        return dateString
    }
//Convert to UTC date only
{{new Date("timestamp from cdr here"*1000).toISOString()}}
//Convert to UTC time and date
{{new Date("timestamp from cdr here"*1000).toISOString().split('T')[0]}}
//Convert to UTC time and date without milliseconds
{{new Date("timestamp from cdr here"*1000).toISOString().slice(0,-8)}}
//Convert to Local time
{{new Date("timestamp from cdr here"*1000).toLocaleString('en-US',{ timeZone: 'America/Chicago' })}}

//Convert YYYY-MM-DD to YYYY-Month Name-DD
{{$node["SplitInBatches"].json["cdr_date"].split('-')[0]}}/{{new Date($node["SplitInBatches"].json["cdr_date"].split('-')[1]).toLocaleString('default', { month: 'long' })}}/{{$node["SplitInBatches"].json["cdr_date"].split('-')[2]}}
[[!SetLocalDate? &date=`[[+publishedon:date=`%d %B %Y`]]`]]
 
 
 <?php
//SetLocalDate
//Converts date format
//Use: [[SetLocalDate? &date=`[[*publishedon]]`]]
  
    $months = array(1 => "Ιανουαρίου",    //January
                     2 => "Φεβρουαρίου", //February
                     3 => "Μαρτίου",      //March
                     4 => "Απριλίου", //April
                     5 => "Μαΐου", //May
                     6 => "Ιουνίου",         //Jun
                     7 => "Ιουλίου",      //July
                     8 => "Αυγούστου", //August
                     9 => "Σεπτεμβρίου",       //September
                     10=> "Οκτωβρίου",    //October
                     11=> "Νοεμβρίου", //November
                     12=> "Δεκεμβρίου");      //December
  
$mj = date("n", strtotime($date));
  
  
// days on Croatian language
       $days = array(1 => "Δευτέρα", // Monday
             2 => "Τρίτη",      //Thuesday
             3 => "Τετάρτη",     //Wensday
             4 => "Πέμπτη",    //Thursday
             5 => "Παρασκευή",        // Friday
             6 => "Σάββατο",       //Saturday
             7 => "Κυριακή");   //Sunday
  
$dy = date("N", strtotime($date));
  
//Get vars
  
$fullday = $days[$dy]; // For example Monday
  
$month = $months[$mj]; // For example January
  
$day = date("d", strtotime($date)); //For example 28
  
$year = date("Y", strtotime($date));// For example 2012
  
  
//display date format for example:
//Ponedjeljak, 24. Prosinac 2012.
  
//return $fullday.', '.$day.'. '.$month.' '.$year.'.';
return $day.' '.$month.' '.$year.'';
const formatDuration = ms => {
  if (ms < 0) ms = -ms;
  const time = {
    day: Math.floor(ms / 86400000),
    hour: Math.floor(ms / 3600000) % 24,
    minute: Math.floor(ms / 60000) % 60,
    second: Math.floor(ms / 1000) % 60,
    millisecond: Math.floor(ms) % 1000
  };
  return Object.entries(time)
    .filter(val => val[1] !== 0)
    .map(([key, val]) => `${val} ${key}${val !== 1 ? 's' : ''}`)
    .join(', ');
};

// Examples
formatDuration(1001); // '1 second, 1 millisecond'
formatDuration(34325055574); // '397 days, 6 hours, 44 minutes, 15 seconds, 574 milliseconds'
star

Wed Feb 21 2024 09:25:30 GMT+0000 (Coordinated Universal Time)

#javascript #date
star

Sun Feb 11 2024 00:22:06 GMT+0000 (Coordinated Universal Time)

#format #date #js #time
star

Thu Feb 08 2024 16:05:17 GMT+0000 (Coordinated Universal Time)

#html #javascript #date #format
star

Thu Dec 07 2023 09:25:10 GMT+0000 (Coordinated Universal Time) https://www.ehansalytics.com/blog/2019/3/17/create-a-dynamic-date-table-in-power-query

#ms.pbi #power.query #date #earliest.date #ms.excel
star

Thu Feb 23 2023 19:17:31 GMT+0000 (Coordinated Universal Time)

#ios #swift #time #date #chat
star

Sat Dec 31 2022 04:27:45 GMT+0000 (Coordinated Universal Time)

#ios #swift #date #picker
star

Sun May 08 2022 04:44:34 GMT+0000 (Coordinated Universal Time)

#c++ #oop #date
star

Tue Apr 19 2022 08:05:37 GMT+0000 (Coordinated Universal Time)

#xml #java #date #format
star

Fri Apr 01 2022 05:39:35 GMT+0000 (Coordinated Universal Time)

#ios #swift #createbutton #currentmonth #date #year
star

Tue Mar 22 2022 20:48:17 GMT+0000 (Coordinated Universal Time) https://bobbyhadz.com/blog/javascript-get-first-day-of-previous-month#:~:text=To%20get%20the%20first%20day,and%201%20for%20the%20day.

#javascript #date
star

Fri Feb 25 2022 12:24:42 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/136782/convert-from-mysql-datetime-to-another-format-with-php

#php #date #mysql
star

Thu Feb 24 2022 07:51:11 GMT+0000 (Coordinated Universal Time)

#ios #swift #day #date #difference
star

Sat Jan 08 2022 09:39:33 GMT+0000 (Coordinated Universal Time)

#ios #swift #date #time #datetime
star

Wed Jul 07 2021 17:07:30 GMT+0000 (Coordinated Universal Time)

##javascript ##n8n #timestamp #date
star

Sun Feb 14 2021 13:24:52 GMT+0000 (Coordinated Universal Time)

#modx #date #locale
star

Sun Nov 29 2020 12:48:42 GMT+0000 (Coordinated Universal Time) https://docs.modx.com/current/en/building-sites/tag-syntax/date-formats

#modx #date #publishedon #format
star

Thu Oct 15 2020 07:34:37 GMT+0000 (Coordinated Universal Time) https://madza.hashnode.dev/24-modern-es6-code-snippets-to-solve-practical-js-problems?guid

#javascript #date

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension