How to Get the Current Date and Time

How to get the current date/time in Java

It depends on what form of date / time you want:

  • If you want the date / time as a single numeric value, then System.currentTimeMillis() gives you that, expressed as the number of milliseconds after the UNIX epoch (as a Java long). This value is a delta from a UTC time-point, and is independent of the local time-zone1.

  • If you want the date / time in a form that allows you to access the components (year, month, etc) numerically, you could use one of the following:

    • new Date() gives you a Date object initialized with the current date / time. The problem is that the Date API methods are mostly flawed ... and deprecated.

    • Calendar.getInstance() gives you a Calendar object initialized with the current date / time, using the default Locale and TimeZone. Other overloads allow you to use a specific Locale and/or TimeZone. Calendar works ... but the APIs are still cumbersome.

    • new org.joda.time.DateTime() gives you a Joda-time object initialized with the current date / time, using the default time zone and chronology. There are lots of other Joda alternatives ... too many to describe here. (But note that some people report that Joda time has performance issues.; e.g. https://stackoverflow.com/questions/6280829.)

    • in Java 8, calling java.time.LocalDateTime.now() and java.time.ZonedDateTime.now() will give you representations2 for the current date / time.

Prior to Java 8, most people who know about these things recommended Joda-time as having (by far) the best Java APIs for doing things involving time point and duration calculations.

With Java 8 and later, the standard java.time package is recommended. Joda time is now considered "obsolete", and the Joda maintainers are recommending that people migrate.3.


1 - System.currentTimeMillis() gives the "system" time. While it is normal practice for the system clock to be set to (nominal) UTC, there will be a difference (a delta) between the local UTC clock and true UTC. The size of the delta depends on how well (and how often) the system's clock is synced with UTC.

2 - Note that LocalDateTime doesn't include a time zone. As the javadoc says: "It cannot represent an instant on the time-line without additional information such as an offset or time-zone."
3 - Note: your Java 8 code won't break if you don't migrate, but the Joda codebase may eventually stop getting bug fixes and other patches. As of 2020-02, an official "end of life" for Joda has not been announced, and the Joda APIs have not been marked as Deprecated.

Getting current date and time in JavaScript

.getMonth() returns a zero-based number so to get the correct month you need to add 1, so calling .getMonth() in may will return 4 and not 5.

So in your code we can use currentdate.getMonth()+1 to output the correct value. In addition:

  • .getDate() returns the day of the month <- this is the one you want
  • .getDay() is a separate method of the Date object which will return an integer representing the current day of the week (0-6) 0 == Sunday etc

so your code should look like this:

var currentdate = new Date(); 
var datetime = "Last Sync: " + currentdate.getDate() + "/"
+ (currentdate.getMonth()+1) + "/"
+ currentdate.getFullYear() + " @ "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();

JavaScript Date instances inherit from Date.prototype. You can modify the constructor's prototype object to affect properties and methods inherited by JavaScript Date instances

You can make use of the Date prototype object to create a new method which will return today's date and time. These new methods or properties will be inherited by all instances of the Date object thus making it especially useful if you need to re-use this functionality.

// For todays date;
Date.prototype.today = function () {
return ((this.getDate() < 10)?"0":"") + this.getDate() +"/"+(((this.getMonth()+1) < 10)?"0":"") + (this.getMonth()+1) +"/"+ this.getFullYear();
}

// For the time now
Date.prototype.timeNow = function () {
return ((this.getHours() < 10)?"0":"") + this.getHours() +":"+ ((this.getMinutes() < 10)?"0":"") + this.getMinutes() +":"+ ((this.getSeconds() < 10)?"0":"") + this.getSeconds();
}

You can then simply retrieve the date and time by doing the following:

var newDate = new Date();
var datetime = "LastSync: " + newDate.today() + " @ " + newDate.timeNow();

Or call the method inline so it would simply be -

var datetime = "LastSync: " + new Date().today() + " @ " + new Date().timeNow();

How do I get the current date in JavaScript?

Use new Date() to generate a new Date object containing the current date and time.

var today = new Date();var dd = String(today.getDate()).padStart(2, '0');var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!var yyyy = today.getFullYear();
today = mm + '/' + dd + '/' + yyyy;document.write(today);

How to get current time and date in Android

You could use:

import java.util.Calendar;
import java.util.Date;

Date currentTime = Calendar.getInstance().getTime();

There are plenty of constants in Calendar for everything you need.

Check the Calendar class documentation.

How to get current date and time in TypeScript

To retrieve the current system Date/Time in javaScript/TypeScript you need to create a new Date object using parameterless constructor, like this:

let dateTime = new Date()

How to get the current date and time

Just construct a new Date object without any arguments; this will assign the current date and time to the new object.

import java.util.Date;

Date d = new Date();

In the words of the Javadocs for the zero-argument constructor:

Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.

Make sure you're using java.util.Date and not java.sql.Date -- the latter doesn't have a zero-arg constructor, and has somewhat different semantics that are the topic of an entirely different conversation. :)

How to get the current time as datetime

Update for Swift 3:

let date = Date()
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)

I do this:

let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute, fromDate: date)
let hour = components.hour
let minutes = components.minute

See the same question in objective-c How do I get hour and minutes from NSDate?

Compared to Nate’s answer, you’ll get numbers with this one, not strings… pick your choice!

How to get current date and time as a constant?

your constant should be initialize at the loading of the page and not on the http request

you should store the value in a variable and not recall moment() when you perform your http request

const time = moment().format("MMMM DD YYYY, hh:mm:ss");

function displayInitTime() {
console.log(time);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<button onClick="displayInitTime()">click me</button>

Getting today's date in YYYY-MM-DD in Python?

Use strftime:

>>> from datetime import datetime
>>> datetime.today().strftime('%Y-%m-%d')
'2021-01-26'

To also include a zero-padded Hour:Minute:Second at the end:

>>> datetime.today().strftime('%Y-%m-%d %H:%M:%S')
'2021-01-26 16:50:03'

To get the UTC date and time:

>>> datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
'2021-01-27 00:50:03'


Related Topics



Leave a reply



Submit