• Home
  • HTML
    • HTML Introduction
    • HTML Basic
    • HTML Elements
    • HTML Attributes
    • HTML Headings
    • HTML Paragraphs
    • HTML Text Formatting
    • HTML Styles
    • HTML Comments
    • HTML Styles - CSS
    • HTML Links
    • HTML Images
    • HTML Tables
    • HTML Lists
    • HTML Block and Inline Elements
    • HTML class Attribute
    • HTML Forms
    • HTML Media
  • CSS
    • Introduction of CSS
    • CSS Syntax
    • CSS Selectors
    • How To Add CSS
    • CSS Comments
    • CSS Colors
    • CSS Backgrounds
    • CSS Borders
    • CSS Margins
    • CSS Text
    • CSS Lists
    • CSS Tables
    • CSS Box Model
    • CSS Dimension
    • CSS Padding
    • CSS Border
    • CSS Margin
    • CSS Outline
    • CSS Cursors
    • CSS Overflow
    • CSS Units
    • CSS Visual Formatting
    • CSS Display
    • CSS Visibility
    • CSS Position
    • CSS Layers
    • CSS Float
    • CSS Alignment
    • CSS Pseudo-classes
    • CSS Pseudo-elements
    • CSS Media Types
    • CSS Sprites
    • CSS Opacity
    • CSS Attribute Selectors
    • CSS Validation
    • CSS3 Border
    • CSS3 Gradients
    • CSS3 Text Overflow
  • JavaScript
    • JS Introduction
    • JS Getting Started
    • JS Syntax
    • JS Variables
    • JS Generating Output
    • JS Data Types
    • JS Operators
    • JS Events
    • JS Strings
    • JS Numbers
    • JS If Else
    • JS Switch Case
    • JS Arrays
    • JS Sorting Arrays
    • JS Loops
    • JS Functions
    • JS Objects
    • JS DOM Nodes
    • JS DOM Selectors
    • JS DOM Styling
    • JS DOM Get Set Attributes
    • JS DOM Manipulation
    • JS DOM Navigation
    • JS Window
    • JS Screen
    • JS Location
    • JS History
    • JS Navigator
    • JS Dialog Boxes
    • JS Timers
    • JS Date and Time
    • JS Math Operations
    • JS Type Conversions
    • JS Event Listeners
    • JS Event Propagation
    • JS Borrowing Methods
    • JS Hoisting Behavior
    • JS Closures
    • JS Strict Mode
    • JS JSON Parsing
    • JS Error Handling
    • JS Regular Expressions
    • JS Form Validation
    • JS Cookies
    • JS AJAX Requests
    • JS ES6 Features
  • jQuery
    • jQuery Introduction
    • jQuery Syntax
    • jQuery Selectors
    • jQuery Events
    • jQuery Show/Hide
    • jQuery Fade
    • jQuery Slide
    • jQuery Animation
    • jQuery Stop
    • jQuery Chaining
    • jQuery Callback
    • jQuery Get/Set
    • jQuery Insert
    • jQuery Remove
    • jQuery CSS Classes
    • jQuery Style Properties
    • jQuery Dimensions
    • jQuery Traversing
    • jQuery Ancestors
    • jQuery Descendants
    • jQuery Siblings
    • jQuery Filtering
    • jQuery Ajax
    • jQuery Load
    • jQuery Get/Post
    • jQuery No-Conflict
  • PHP
    • PHP Introduction
    • PHP Install
    • PHP Syntax
    • PHP Comments
    • PHP Variables
    • PHP Echo / Print
    • PHP Data Types
    • PHP Strings
    • PHP Constants
    • PHP Operators
    • PHP If...Else...Elseif
    • PHP Switch
    • PHP Loops
    • PHP Functions
    • PHP Arrays
    • PHP Superglobals
    • PHP Date and Time
    • PHP Include
    • PHP File Handling
    • PHP File Upload
    • PHP Cookies
    • PHP Sessions
    • PHP Filters
    • PHP Callback Functions
    • PHP JSON
    • PHP Exceptions
    • PHP What is OOP
    • PHP Classes/Objects
    • PHP Constructor
    • PHP Destructor
    • PHP Access Modifiers
    • PHP Inheritance
    • PHP Abstract Classes
    • PHP Interfaces
    • PHP Traits
    • PHP Static Methods
    • PHP Namespaces
  • SQL
    • Introduction to SQL
    • SQL Create Command
    • SQL ALTER Command
    • SQL Truncate Drop Rename
    • INSERT SQL command
    • UPDATE SQL command
    • DELETE SQL command
    • SQL COMMIT command
    • SQL ROLLBACK command
    • SQL GRANT and REVOKE Command
    • SQL WHERE clause
    • SQL LIKE clause
    • SQL ORDER BY Clause
    • SQL Group By Clause
    • SQL HAVING Clause
    • SQL DISTINCT keyword
    • SQL AND OR operator
    • SQL Constraints
    • SQL Functions
    • SQL JOIN
  • Python
    • Getting started with Python
    • Introduction to IDLE
    • Python 2.x vs. Python 3.x
    • Syntax Rules and First Program
    • Numbers and Math Functions
    • Python Operators
    • Python Variables
    • Python Modules and Functions
    • Python Input and Output
    • Data Types in Python
    • String in Python
    • String Functions in python
    • Lists in Python
    • Utilizing List Elements by Iterating
    • Deleting List Elements & other Functions
    • Dictionaries in Python
    • Functions for Dictionary
    • Tuples in Python
    • Relational and Logical Operators
    • Conditional Statements in Python
    • Looping in Python
    • Define Functions in Python
    • Python-Introduction to OOP
    • Object Oriented Programming in Python
    • Classes in Python
    • The concept of Constructor
    • Destructors - Destroying the Object in Python
    • Inheritance in Python
    • Access Modifers in Python
    • Types of Inheritance
    • Method Overriding in Python
    • Polymorphism
    • static Keyword
    • Operator Overloading Python
    • Introduction to Error Handling
    • Exception Handling: try and except
    • Exeption Handling: finally
    • Exception Handling: raise
    • File Handling
    • Reading and Writing File
    • Introduction to Multithreading
    • Threading Module in Python
    • Thread Object
    • Lock Object
    • RLock Object
    • Event Object
    • Timer Object
    • Condition Object
    • Barrier Object
    • __name__ Variable in Python
    • Iterable and Iterator
    • yield Keyword
    • Python Generators
    • Python Closures
    • Python Decorators
    • @property Decorator in Python
    • Assert Statement
    • Garbage Collection
    • Shallow and Deep Copy
    • Introduction to Logging
    • Configure Log LEVEL, Format etc
    • Python Logging in a file
    • Python Logging Variable Data
    • Python Logging Classes and Functions
    • Python MySQL Introduction
    • Create Database - Python MySQL
    • Create Table - Python MySQL
    • Insert Data in Table
    • Select Data from Table
    • Update data in Table
    • Delete data from Table
    • Drop Table from Database
    • WHERE clause - Python MySQL
    • Order By clause - Python MySQL
    • Limit clause - Python MySQL
    • Table Joins - Python MySQL
  • MongoDB
    • MongoDB Introduction
    • Overview of MongoDB
    • MongoDB vs SQL Databases
    • Advantages of MongoDB
    • When to go for MongoDB
    • Data Modelling in MongoDB
    • Is MongoDB really Schemaless?
    • Installing MongoDB on Windows and Linux
    • Datatypes in MongoDB
    • Create and Drop Database in MongoDB
    • MongoDB: Creating a Collection
    • CRUD Operations in MongoDB
    • Data Relationships in MongoDB
    • Indexing in MongoDB
    • Sorting in MongoDB
    • Aggregation in MongoDB
    • Data Backup and Restoration in MongoDB
    • Sharding in MongoDB
    • Java Integration with MongoDB
  • Elixir
    • Elixir Overview
    • Elixir Environment
    • Elixir Basic Syntax
    • Elixir Data Types
    • Elixir Variables
    • Elixir Operators
    • Elixir Pattern Matching
    • Elixir Decision Making
    • Elixir Strings
    • Elixir Char Lists
    • Elixir Lists and Tuples
    • Elixir Keyword Lists
    • Elixir Maps
    • Elixir Modules
    • Elixir Aliases
    • Elixir Functions
    • Elixir Recursion
    • Elixir Loops
    • Elixir Enumerables
    • Elixir Streams
    • Elixir Structs
    • Elixir Protocols
    • Elixir File I/O
    • Elixir Processes
    • Elixir Sigils
    • Elixir Comprehensions
    • Elixir Typespecs
    • Elixir Behaviours
    • Elixir Errors Handling
    • Elixir Macros
    • Elixir Libraries
  • TypeScript
    • TypeScript Overview
    • Install TypeScript
    • First TypeScript Program
    • Type Annotation
    • TypeScript Variable
    • TypeScript Data Type Number
    • TypeScript Data Type String
    • TypeScript Data Type Boolean
    • TypeScript Arrays
    • TypeScript Tuples
    • TypeScript Enum
    • TypeScript Union
    • TypeScript Any Data Type
    • TypeScript Void Data Type
    • TypeScript Never Data Type
  • Home
  • JS Introduction
  • JS Getting Started
  • JS Syntax
  • JS Variables
  • JS Generating Output
  • JS Data Types
  • JS Operators
  • JS Events
  • JS Strings
  • JS Numbers
  • JS If Else
  • JS Switch Case
  • JS Arrays
  • JS Sorting Arrays
  • JS Loops
  • JS Functions
  • JS Objects
  • JS DOM Nodes
  • JS DOM Selectors
  • JS DOM Styling
  • JS DOM Get Set Attributes
  • JS DOM Manipulation
  • JS DOM Navigation
  • JS Window
  • JS Screen
  • JS Location
  • JS History
  • JS Navigator
  • JS Dialog Boxes
  • JS Timers
  • JS Date and Time
  • JS Math Operations
  • JS Type Conversions
  • JS Event Listeners
  • JS Event Propagation
  • JS Borrowing Methods
  • JS Hoisting Behavior
  • JS Closures
  • JS Strict Mode
  • JS JSON Parsing
  • JS Error Handling
  • JS Regular Expressions
  • JS Form Validation
  • JS Cookies
  • JS AJAX Requests
  • JS ES6 Features
Home >> javascript >> JS Date and Time

JS Date and Time

Welcome to another tutorial, here you will learn how to work with data and time in JavaScript.
 

Using the Date Object

In JavaScript, a date object is a built-in object. The date object makes it possible for you to get the user's local time by accessing the computer system clock through the browser. It also provides several methods for managing, formatting, and manipulating dates and times.

 

Creating a Date Object

You need to learn how to create a Date object before you start working with the date and time. However, dates don't have a corresponding literal form (i.e all data objects need to be created using the Date constructor function which is Date()), unlike other built-in objects, such as arrays or functions.

In JavaScript, there are four different ways to create a Date object.

 

The new Date() Syntax

A new Date object can simply be declared without initializing its value. Hence, the date and time value will be set to the current date and time on the user's device on which the script is run. 

 

The new Date(year, month, ...) Syntax

A Date object can be initialized by passing the following parameters separated by the use of commas: year, month, day, hours, minutes, seconds, and milliseconds. The year and month parameters are important while, other parameters are optional. 

var d = new Date(2022,07,15,14,35,20,50);
document.write(d);

Try with example

This date is represented as 15 Aug 2022 at 14:35:20 and 50 milliseconds, but you can ignore the time part and specify just the date part if you wish.

 

The new Date(dateString) Syntax

In JavaScript, you to create a Date object by passing the string representing a date, or a date and time, as shown in the example below:

var d = new Date("15 April 2022");
document.write(d);

Try with example

This date represents 15 April 2022, but, you can also specify strings like ‘Apr 15, 2022’, or any of a number of valid variations, as JavaScript will automatically handle that.

 

The new Date(milliseconds) Syntax

A Date object can also be defined by passing the number of milliseconds since January 1, 1970, at 00:00:00 GMT. This is because1970 was the year when the UNIX operating system was formally introduced and is known as the UNIX epoch 

var d = new Date(1660458141499);
document.write(d);

Try with example

The date in the example above represents Sun Aug 14 2022 11:52:21 05:30:00 GMT+0530.

When you have created an instance of the Date object, you can then use its methods to perform various tasks, like getting different components of a date, setting or modifying the individual date and time value, and so on. 

In the next sections, we will look at these methods in detail.

Note: The shortcuts called "literals" are provided by JavaScript for creating most of the native objects without having to use the new operator, like new Object(), new Array(), and so on.

 

Getting the Current Date and Time

To get the current date and time, you can create a new Date object without passing any parameters. However, it will create an object with the current date and time. below is an example: 

var now = new Date();
alert(now); // Display the current date and time

Try with example

The output of the example above will look like this (depending on time zone offset):

 

Creating the Date and Time Strings

The JavaScript Date object provides numerous methods, including toLocaleDateString(), toDateString(), and so on.

If you want to generate date strings in different formats. You can do it like this: 

var d = new Date();
alert(d.toDateString()); // Display an abbreviated date string
alert(d.toLocaleDateString()); // Display a localized date string
alert(d.toISOString()); // Display the ISO standardized date string
alert(d.toUTCString()); // Display a date string converted to UTC time
alert(d.toString()); // Display the full date string with local time zone

Try with example

More so, you can also use the toTimeString(), toLocaleTimeString() methods of the Date object to generate time strings, as shown in the example below:

var d = new Date();
alert(d.toTimeString()); // Display the time portion of the date
alert(d.toLocaleTimeString()); // Display a localized time string

Try with example

 

Getting Specific Date and Time Components

Once you have a well-defined date object, several methods are available to you for the extraction details from it; such as the month, date, hours or minutes value, etc.

The sections below describe the various methods of extracting individual pieces of information from a Date object.

 

Getting the Year, Month and Date

The methods such as getFullYear(), getMonth(), getDay(), are provided by the Date object, that you can use to extract the specific date components from the Date object, such as year, day of the month, day of the week, and so on respectively. The example illustrates how to get specific date components from the Date object using these methods:

var d = new Date();
// Extracting date part
alert(d.getDate()); // Display the day of the month
alert(d.getDay()); // Display the number of days into the week (0-6)
alert(d.getMonth()); // Display the number of months into the year (0-11)
alert(d.getFullYear()); // Display the full year (four digits)

Try with example

 

The method getDay() returns a number representing the day of the week (i.e from 0 to 6) instead of returning a name such as Sunday or Monday in such a way that. This means that, if it is Sunday, the method returns 0; and if it is Monday, the method returns 1, and so on.

Same here also, the getMonth() method returns the number of months (i.e from 0 to 11) instead of the name of the month. Just like above, 0 represents the first month of the year, so if it is January the method returns 0, not 1; and if it is August, the method returns 7 and not 8.

 

Getting the Hours, Minutes, Seconds, and Milliseconds

More so, the Date object provides methods like getHours(), getMinutes(), getSeconds(),  getTimezoneOffset() and so on. They are used to extract the time components from the Date object.

var d = new Date();
// Extracting time part 
alert(d.getHours()); // Display the number of hours into the day (0-23)
alert(d.getMinutes()); // Display the number of minutes into the hour (0-59)
alert(d.getSeconds()); // Display the seconds into the minute (0-59)
alert(d.getMilliseconds()); // Display the number of milliseconds into second (0-999)
alert(d.getTime()); // Display the number of milliseconds since 1/1/1970
alert(d.getTimezoneOffset()); // Display the time-zone offset (from Greenwich Mean Time) in minutes

Try with example

 

The method getHours() returns the number of hours into the day (i.e. from 0 to 23) according to the 24-hour clock. Therefore, when it is midnight, the getHours() method returns 0; and when it is 3:00 P.M., it returns 15.

Note: The Date objects also have methods to obtain the UTC components, such as getUTCDate(), getUTCHour(), getUTCMinutes(), and so on.

 

Setting the Date and Time Values

More so, to retrieve date and time values, you can set or modify these values using the JavaScript. This approach is most often used in a program that requires you to change the value of a date object from one particular date or time to another.

 

Setting the Year, Month and Date

The Date object also provides methods such as setFullYear(),  setMonth(), and setDate() methods to set the year, month, and date components of the Date object respectively.

In the example below, we have used setFullYear() method to change the current date stored in a variable ahead of two years in the future.+ 2).

var d = new Date();
d.setFullYear(d.getFullYear() + 2);
alert(d); // Display future date

Try with example

However, you can use the setMonth() method to set or modify the month part of a Date object. 

var d = new Date(); // Current date and time
d.setMonth(0); // Sets month to 0, January
document.write(d);

Try with example

 

It requires an integer value from 0 to 11. But, if you set the value of the month greater than 11, the year value of the date object will increment.

In other words, a value of 12 produces results in the year value that increases by 1, and the month value set to 0, as illustrated in the example below:

var d = new Date(2022, 7, 15); // August 15, 2022
d.setMonth(12); // Sets month to 12, new date will be August 15, 2023
document.write(d);

Try with example

 

Also, the date part of the date object can be modified, like this;

var d = new Date(2022, 7, 1); // August 1, 2022
    d.setDate(15); // Sets date to 15, new date will be August 15, 2022
    document.write(d);

Try with example

 

The setDate() method takes an integer value starting from 1 to 31. however, if you pass the values greater than the number of days in the month, it will cause an increment in the month. Take a look at the example:

var d = new Date(2022, 7, 15); // June 24, 2018
d.setDate(36); // Sets day to 36, new date will be Sep 5, 2022
document.write(d);

Try with example

 

Setting the Hours, Minutes and Seconds

Methods for setting the time values are straightforward. In the Date object, setHours(), setMinutes(), setSeconds(), setMilliseconds() can be used to set the hour, minutes, seconds, and milliseconds part respectively.

All the methods in the Date object take integer values as parameters. For instance, Hours range from 0 to 23; Minutes and seconds range from 0 to 59; milliseconds range from 0 to 999. This is illustrated in the example below:

var d = new Date(2022, 7, 15); // Aug 15, 2022 00:00:00
d.setHours(8);
d.setMinutes(30);
d.setSeconds(45);
d.setMilliseconds(600);
document.write(d);

Try with example

 

  • Prev
  • Next


-Advertisement-


DeveloperTutorial
[email protected] © 2022-2023 Developers Tutorial All rights reserved.

Follow Us

Facebook Twitter LinkedIn Printerest Reddit

Announcement

Its a big achivement for us, We make a partnership with TutorialWithExample.com for the better content of our users.

Still Need Help ?

Let us now about your issue and a Professional will reach you out.