[javascript] How do I get the time of day in javascript/Node.js?

I want to get 1 to 24, 1 being 1am Pacific Time.

How can I get that number in Node.JS?

I want to know what time it is in Pacific time right now.

This question is related to javascript datetime date node.js

The answer is


var date = new Date();
var year = date.getFullYear();
var month = date.getMonth() + 1;
month = (month < 10 ? "0" : "") + month;
var hour = date.getHours();
hour = (hour < 10 ? "0" : "") + hour;
var day  = date.getDate();
day = (hour > 12 ? "" : "") + day - 1;
day = (day < 10 ? "0" : "") + day;
x = ":"
console.log( month + x + day + x + year )

It will display the date in the month, day, then the year


This function will return you the date and time in the following format: YYYY:MM:DD:HH:MM:SS. It also works in Node.js.

function getDateTime() {

    var date = new Date();

    var hour = date.getHours();
    hour = (hour < 10 ? "0" : "") + hour;

    var min  = date.getMinutes();
    min = (min < 10 ? "0" : "") + min;

    var sec  = date.getSeconds();
    sec = (sec < 10 ? "0" : "") + sec;

    var year = date.getFullYear();

    var month = date.getMonth() + 1;
    month = (month < 10 ? "0" : "") + month;

    var day  = date.getDate();
    day = (day < 10 ? "0" : "") + day;

    return year + ":" + month + ":" + day + ":" + hour + ":" + min + ":" + sec;

}

If you only want the time string you can use this expression (with a simple RegEx):

new Date().toISOString().match(/(\d{2}:){2}\d{2}/)[0]
// "23:00:59"

For my instance i used it as a global and then called its for a time check of when hours of operation.

Below is from my index.js

global.globalDay = new Date().getDay(); 

global.globalHours = new Date().getHours();

To call the global's value from another file

    /*
     Days of the Week.
     Sunday = 0, Monday = 1, Tuesday = 2, Wensday = 3, Thursday = 4, Friday = 5, Saturday = 6

     Hours of the Day.
     0 = Midnight, 1 = 1am, 12 = Noon, 18 = 6pm, 23 = 11pm
     */

if (global.globalDay === 6 || global.globalDay === 0) {
     console.log('Its the weekend.');
} else if (global.globalDay > 0 && global.globalDay < 6 && global.globalHours > 8 && global.globalHours < 18) {
     console.log('During Business Hours!');
} else {
     console.log("Outside of Business hours!");
}

Both prior answers are definitely good solutions. If you're amenable to a library, I like moment.js - it does a lot more than just getting/formatting the date.


To start your node in PST time zone , use following command in ubuntu.

TZ=\"/usr/share/zoneinfo/GMT+0\" && export TZ && npm start &

Then You can refer Date Library to get the custom calculation date and time functions in node.

To use it client side refer this link, download index.js and assertHelper.js and include that in your HTML.

<script src="assertHelper.js"></script>
<script type="text/javascript" src="index.js"></script>
$( document ).ready(function() {
    DateLibrary.getDayOfWeek(new Date("2015-06-15"),{operationType:"Day_of_Week"}); // Output : Monday
}

You can use different functions as given in examples to get custom dates.

If first day of week is Sunday, what day will be on 15th June 2015.

 DateLibrary.getDayOfWeek(new Date("2015-06-15"),
    {operationType:"Day_Number_of_Week",
        startDayOfWeek:"Sunday"}) // Output : 1

If first day of week is Tuesday, what week number in year will be follow in 15th June 2015 as one of the date.

 DateLibrary.getWeekNumber(new Date("2015-06-15"),
    {operationType:"Week_of_Year",
        startDayOfWeek:"Tuesday"}) // Output : 24

Refer other functions to fulfill your custom date requirements.


There's native method to work with date

const date = new Date();
let hours = date.getHours();

Check out the moment.js library. It works with browsers as well as with Node.JS. Allows you to write

moment().hour();

or

moment().hours();

without prior writing of any functions.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to datetime

Comparing two joda DateTime instances How to format DateTime in Flutter , How to get current time in flutter? How do I convert 2018-04-10T04:00:00.000Z string to DateTime? How to get current local date and time in Kotlin Converting unix time into date-time via excel Convert python datetime to timestamp in milliseconds SQL Server date format yyyymmdd Laravel Carbon subtract days from current date Check if date is a valid one Why is ZoneOffset.UTC != ZoneId.of("UTC")?

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`