Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
JavaScript

JavaScript: Working with Dates and Times

- 16.08.26 - ErcanOPAK

📅 Date and Time = JavaScript

Dates are tricky. JavaScript date handling helps you manage dates and times effectively.

📝 Date Operations

// Create Date
const now = new Date();
const specific = new Date(2024, 0, 15); // Jan 15, 2024
const fromString = new Date('2024-01-15T10:00:00');

// Format Date
const date = new Date();
date.toLocaleDateString(); // '1/15/2024'
date.toLocaleString(); // '1/15/2024, 10:00:00 AM'
date.toISOString(); // '2024-01-15T10:00:00.000Z'

// Get Date Components
const year = date.getFullYear();
const month = date.getMonth(); // 0-11
const day = date.getDate();
const hours = date.getHours();
const minutes = date.getMinutes();

// Date Arithmetic
const future = new Date(date);
future.setDate(future.getDate() + 7); // Add 7 days
future.setMonth(future.getMonth() + 1); // Add 1 month
future.setFullYear(future.getFullYear() + 1); // Add 1 year

// Compare Dates
const date1 = new Date('2024-01-15');
const date2 = new Date('2024-01-16');
date1 < date2; // true

🎯 Advanced Date Patterns

// Date Utilities
class DateUtils {
    static format(date, format) {
        const map = {
            'YYYY': date.getFullYear(),
            'MM': String(date.getMonth() + 1).padStart(2, '0'),
            'DD': String(date.getDate()).padStart(2, '0'),
            'HH': String(date.getHours()).padStart(2, '0'),
            'mm': String(date.getMinutes()).padStart(2, '0'),
            'ss': String(date.getSeconds()).padStart(2, '0')
        };
        return format.replace(/YYYY|MM|DD|HH|mm|ss/g, match => map[match]);
    }

    static addDays(date, days) {
        const result = new Date(date);
        result.setDate(result.getDate() + days);
        return result;
    }

    static getTimeAgo(date) {
        const diff = Date.now() - date.getTime();
        const seconds = Math.floor(diff / 1000);
        const minutes = Math.floor(seconds / 60);
        const hours = Math.floor(minutes / 60);
        const days = Math.floor(hours / 24);

        if (days > 0) return `${days} days ago`;
        if (hours > 0) return `${hours} hours ago`;
        if (minutes > 0) return `${minutes} minutes ago`;
        return 'Just now';
    }

    static isWeekend(date) {
        const day = date.getDay();
        return day === 0 || day === 6;
    }

    static getDaysInMonth(year, month) {
        return new Date(year, month + 1, 0).getDate();
    }
}

// Moment-like API (Lightweight)
class DateTime {
    constructor(date) {
        this.date = new Date(date);
    }

    format(format) {
        return DateUtils.format(this.date, format);
    }

    addDays(days) {
        return new DateTime(DateUtils.addDays(this.date, days));
    }

    fromNow() {
        return DateUtils.getTimeAgo(this.date);
    }
}

💡 Date Tips

  • Use ISO format for storage
  • Handle timezones carefully
  • Use UTC for backend
  • Format for display locally
  • Use libraries for complex operations

Date handling in JavaScript can be tricky. These patterns make it manageable and consistent.

— JavaScript Developer

Related posts:

How to format date in Javascript

How to format date in Javascript

JavaScript: Understand Hoisting

JavaScript: Understand Hoisting

Step-by-Step: Building a Weather App with Fetch API

Step-by-Step: Building a Weather App with Fetch API

Views: 5

Post navigation

HTML: Using ARIA Roles for Better Accessibility
AJAX: Implementing Pagination in REST APIs

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

November 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
30  
« Oct    

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,055)
  • Get the User Name and Domain Name from an Email Address in SQL (980)
  • How to add default value for Entity Framework migrations for DateTime and Bool (977)
  • Get the First and Last Word from a String or Sentence in SQL (858)
  • How to select distinct rows in a datatable in C# (854)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (653)
  • Add Constraint to SQL Table to ensure email contains @ (609)
  • Average of all values in a column that are not zero in SQL (570)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (547)
  • Find numbers with more than two decimal places in SQL (475)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit
  • SQL Server: Fix ROW_NUMBER Ties Reordering Between Identical Runs
  • C#: Fix an Enum HasFlag Returning True for the Zero Value
  • WordPress: Fix Featured Images Vanishing After a CDN Migration
  • Photoshop: Fix Content-Aware Fill Smearing a Repeating Pattern
  • Asp.Net Core: Fix Antiforgery Tokens Rejected Behind a Reverse Proxy

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,055)
  • Get the User Name and Domain Name from an Email Address in SQL (980)
  • How to add default value for Entity Framework migrations for DateTime and Bool (977)
  • Get the First and Last Word from a String or Sentence in SQL (858)
  • How to select distinct rows in a datatable in C# (854)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com