javascript date format yyyy-mm-dd HH:MM:ss [duplicate] - javascript

This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 2 years ago.
I have facing an issue in javascript date format all dates in this format yyyy-mm-dd HH:MM:ss
My Code:
var currentdate = new Date();
var prevdate = new Date();
var firstdate = new Date();
prevdate.setTime(currentdate.getTime() - (30 * 60 * 1000));
firstdate.setTime(currentdate.getTime() + (30 * 60 * 1000));
var current = currentdate.toLocaleTimeString();
var previous = prevdate.toLocaleTimeString();
var first = firstdate.toLocaleTimeString();
console data
console.log(previous); //10:28:24 PM
console.log(current); //10:58:24 PM
console.log(first); //11:28:24 PM
I try this , how can i pass previous and first date
var Currentdate=dateFormat(new Date(), "yyyy-mm-dd HH:MM:ss");
console.log("Currentdate"); //2020-05-07 22:58:11
Expected Output Date Format: yyyy-mm-dd HH:MM:ss
previous date: 2020-05-07 22:28:11 // date before 30min
current date: 2020-05-07 22:58:11 // current date
first date: 2020-05-07 23:28:11 // date after 30min
What should i do? can anyone help?

You should use currentdate.toLocaleString() instead, as toLocaleTimeString()
returns a string with a language sensitive representation of the time portion of this date
toLocaleString
toLocaleTimeString

Use toLocaleString instead of toLocaleTimeString

Hi please try th following function:
function getTime(){
var date = new Date();
console.log(GetFormattedDate(date));
}
function GetFormattedDate(date) {
var month = ("0" + (date.getMonth() + 1)).slice(-2);
var day = ("0" + (date.getDate())).slice(-2);
var year = date.getFullYear();
var hour = ("0" + (date.getHours())).slice(-2);
var min = ("0" + (date.getMinutes())).slice(-2);
var seg = ("0" + (date.getSeconds())).slice(-2);
return year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + seg;
}
in your case
function getTime(){
var date = new Date();
var currentdate = new Date();
var prevdate = new Date();
var firstdate = new Date();
prevdate.setTime(currentdate.getTime() - (30 * 60 * 1000));
firstdate.setTime(currentdate.getTime() + (30 * 60 * 1000));
console.log(GetFormattedDate(prevdate));
console.log(GetFormattedDate(currentdate));
console.log(GetFormattedDate(firstdate));
}
function GetFormattedDate(date) {
var month = ("0" + (date.getMonth() + 1)).slice(-2);
var day = ("0" + (date.getDate())).slice(-2);
var year = date.getFullYear();
var hour = ("0" + (date.getHours())).slice(-2);
var min = ("0" + (date.getMinutes())).slice(-2);
var seg = ("0" + (date.getSeconds())).slice(-2);
return year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + seg;
}
regards

You need to use toLocaleString
var currentdate = new Date();
var prevdate = new Date();
var firstdate = new Date();
prevdate.setTime(currentdate.getTime() - (30 * 60 * 1000));
firstdate.setTime(currentdate.getTime() + (30 * 60 * 1000));
var options = { hour12: false };
var current = currentdate.toLocaleString('en-US', options);
var previous = prevdate.toLocaleString('en-US', options);
var first = firstdate.toLocaleString('en-US', options);
current = current.replace(/\//g, '-');
previous = previous.replace(/\//g, '-');
first = first.replace(/\//g, '-');
console.log(`current: ${current}`);
console.log(`previous: ${previous}`);
console.log(`first: ${first}`);

Related

Current Date converted to 10 days before and 10 days after

I have this code where I convert the current date to this format 2020-08-20 . But how do I alter it to give me the date 10 days from today and 10 days before today.
eg today is 2020-08-20 I am trying to get 10 days from today 2020-08-30
This is my code
const dateConverter = (dateIn) => {
var year = dateIn.getFullYear();
var month = dateIn.getMonth() + 1; // getMonth() is zero-based
var day = dateIn.getDate();
return year + "-" + month.toString().padStart(2, "0") + "-" + day.toString().padStart(2, "0");
}
var today = new Date();
console.log(dateConverter(today));
It's a little bit tricky. First set the hours from the date to 12 for avoiding problems with summer/wintertime-changing. Then use getDate add 10 for the extra days and setDate with the new value. Now you have a value in milliseconds, generate out of this a new date to get an dateobject. For the second date subtract 20 days because the original date was changed by the action before and do all other the same.
Format the output for the dates with getFullYear, getMonth and getDate
. Because month is handled in JS from 0 to 11 add 1 month. Months and days could be 1-digit but you want it 2 digits, so add before the string "0" and get the last 2 chars of it with slice.
Do the format for both dates and return them as array.
const dateConverter = (dateIn) => {
dateIn.setHours(12);
let dateIn10days = new Date(dateIn.setDate(dateIn.getDate() + 10));
let dateFor10days = new Date(dateIn.setDate(dateIn.getDate() - 20));
let strIn10Days = dateIn10days.getFullYear() + '-' + ('0' +(dateIn10days.getMonth()+1)).slice(-2) + '-' + ('0' + dateIn10days.getDate()).slice(-2);
let strFor10Days = dateFor10days.getFullYear() + '-' + ('0' +(dateFor10days.getMonth()+1)).slice(-2) + '-' + ('0' + dateFor10days.getDate()).slice(-2);
return [strFor10Days, strIn10Days];
}
let today = new Date();
console.log(dateConverter(today));
Try this
const dateConverter = (dateIn) => {
var year = dateIn.getFullYear();
var month = dateIn.getMonth() + 1; // getMonth() is zero-based
var day = dateIn.getDate();
return year + "-" + month.toString().padStart(2, "0") + "-" + day.toString().padStart(2, "0");
}
var today = new Date();
var numberOfDaysToAdd = 10;
var tenDaysPlus = today.setDate(today.getDate() + numberOfDaysToAdd);
console.log(dateConverter(today));
var today = new Date();
var numberOfDaysToSubtract = 10;
var tenDaysMinus = today.setDate(today.getDate() - numberOfDaysToSubtract);
console.log(dateConverter(today));
I would suggest you to use the moment library but you still want plain javascript
const convert = (date) => {
const pastDate = new Date(date)
pastDate.setDate(pastDate.getDate() - 10);
const futureDate = new Date(date)
futureDate.setDate(futureDate.getDate() + 10);
return { pastDate, futureDate }
}
call convert function with any date.
This code will help you
Reference JavaScript calculating date from today date to 7 days before
for after 10 days just just convert the - to +
const dateConverter = (dateIn) => {
var dates ={};
var days = 10; // Days you want to subtract
for(let i=0;i<days;i++){
var date = dateIn;
var last = new Date(date.getTime() - (i * 24 * 60 * 60 * 1000));
var day = last.getDate();
var month= last.getMonth()+1;
var year= last.getFullYear();
dates[i] = year + "-" + month.toString().padStart(2, "0") + "-" + day.toString().padStart(2, "0");
}
return dates
}
var today = new Date();
console.log(dateConverter(today));
I've been messing around that before as well.
But on this Stack Overflow you can find a really good answer:
Add days to JavaScript Date
Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
var date = new Date();
alert(date.addDays(5));
This is the code taken from that post.
For subtracting days, just replace the "+ days" with "- days"
Hope this solved your problem!
You can convert all the dates to timestamp and then simply calculate with them:
const dateTimestamp = new Date("2020-10-10").getTime()
const milisecondsInADay = 60*60*24*1000
const milisecondsInTenDays = milisecondsInADay * 10
const beforeDate = new Date(dateTimestamp - milisecondsInTenDays)
const afterDate = new Date(dateTimestamp + milisecondsInTenDays)
console.log("before", beforeDate)
console.log("after", afterDate)
console.log("initially", new Date(dateTimestamp))

Convert a timestamp to YYYY-MM-DD with JS [duplicate]

I am storing time in a MySQL database as a Unix timestamp and that gets sent to some JavaScript code. How would I get just the time out of it?
For example, in HH/MM/SS format.
let unix_timestamp = 1549312452
// Create a new JavaScript Date object based on the timestamp
// multiplied by 1000 so that the argument is in milliseconds, not seconds.
var date = new Date(unix_timestamp * 1000);
// Hours part from the timestamp
var hours = date.getHours();
// Minutes part from the timestamp
var minutes = "0" + date.getMinutes();
// Seconds part from the timestamp
var seconds = "0" + date.getSeconds();
// Will display time in 10:30:23 format
var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
console.log(formattedTime);
For more information regarding the Date object, please refer to MDN or the ECMAScript 5 specification.
function timeConverter(UNIX_timestamp){
var a = new Date(UNIX_timestamp * 1000);
var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var year = a.getFullYear();
var month = months[a.getMonth()];
var date = a.getDate();
var hour = a.getHours();
var min = a.getMinutes();
var sec = a.getSeconds();
var time = date + ' ' + month + ' ' + year + ' ' + hour + ':' + min + ':' + sec ;
return time;
}
console.log(timeConverter(0));
JavaScript works in milliseconds, so you'll first have to convert the UNIX timestamp from seconds to milliseconds.
var date = new Date(UNIX_Timestamp * 1000);
// Manipulate JavaScript Date object here...
Use:
var s = new Date(1504095567183).toLocaleDateString("en-US")
console.log(s)
// expected output "8/30/2017"
and for time:
var s = new Date(1504095567183).toLocaleTimeString("en-US")
console.log(s)
// expected output "3:19:27 PM"
see Date.prototype.toLocaleDateString()
Modern Solution (for 2020)
In the new world, we should be moving towards the standard Intl JavaScript object, that has a handy DateTimeFormat constructor with .format() method:
function format_time(s) {
const dtFormat = new Intl.DateTimeFormat('en-GB', {
timeStyle: 'medium',
timeZone: 'UTC'
});
return dtFormat.format(new Date(s * 1e3));
}
console.log( format_time(12345) ); // "03:25:45"
Eternal Solution
But to be 100% compatible with all legacy JavaScript engines, here is the shortest one-liner solution to format seconds as hh:mm:ss:
function format_time(s) {
return new Date(s * 1e3).toISOString().slice(-13, -5);
}
console.log( format_time(12345) ); // "03:25:45"
Method Date.prototype.toISOString() returns time in
simplified extended ISO 8601 format, which is always 24 or 27 characters long (i.e. YYYY-MM-DDTHH:mm:ss.sssZ or
±YYYYYY-MM-DDTHH:mm:ss.sssZ respectively). The timezone is always
zero UTC offset.
This solution does not require any third-party libraries and is supported in all browsers and JavaScript engines.
I'm partial to Jacob Wright's Date.format() library, which implements JavaScript date formatting in the style of PHP's date() function.
new Date(unix_timestamp * 1000).format('h:i:s')
I'd think about using a library like momentjs.com, that makes this really simple:
Based on a Unix timestamp:
var timestamp = moment.unix(1293683278);
console.log( timestamp.format("HH/mm/ss") );
Based on a MySQL date string:
var now = moment("2010-10-10 12:03:15");
console.log( now.format("HH/mm/ss") );
shortest one-liner solution to format seconds as hh:mm:ss: variant:
console.log(new Date(1549312452 * 1000).toISOString().slice(0, 19).replace('T', ' '));
// "2019-02-04 20:34:12"
In moment you must use unix timestamp:
const dateTimeString = moment.unix(1466760005).format("DD-MM-YYYY HH:mm:ss");
This works with PHP timestamps
var d = 1541415288860;
//var d =val.timestamp;
//NB: use + before variable name
var date = new Date(+d);
console.log(d);
console.log(date.toDateString());
console.log(date.getFullYear());
console.log(date.getMinutes());
console.log(date.getSeconds());
console.log(date.getHours());
console.log(date.toLocaleTimeString());
var d =val.timestamp;
var date=new Date(+d); //NB: use + before variable name
console.log(d);
console.log(date.toDateString());
console.log(date.getFullYear());
console.log(date.getMinutes());
console.log(date.getSeconds());
console.log(date.getHours());
console.log(date.toLocaleTimeString());
the methods above will generate this results
1541415288860
Mon Nov 05 2018
2018
54
48
13
1:54:48 PM
There's a bunch of methods that work perfectly with timestamps. Cant list them all
UNIX timestamp is number of seconds since 00:00:00 UTC on January 1, 1970 (according to Wikipedia).
Argument of Date object in Javascript is number of miliseconds since 00:00:00 UTC on January 1, 1970 (according to W3Schools Javascript documentation).
See code below for example:
function tm(unix_tm) {
var dt = new Date(unix_tm*1000);
document.writeln(dt.getHours() + '/' + dt.getMinutes() + '/' + dt.getSeconds() + ' -- ' + dt + '<br>');
}
tm(60);
tm(86400);
gives:
1/1/0 -- Thu Jan 01 1970 01:01:00 GMT+0100 (Central European Standard Time)
1/0/0 -- Fri Jan 02 1970 01:00:00 GMT+0100 (Central European Standard Time)
Using Moment.js, you can get time and date like this:
var dateTimeString = moment(1439198499).format("DD-MM-YYYY HH:mm:ss");
And you can get only time using this:
var timeString = moment(1439198499).format("HH:mm:ss");
The problem with the aforementioned solutions is, that if hour, minute or second, has only one digit (i.e. 0-9), the time would be wrong, e.g. it could be 2:3:9, but it should rather be 02:03:09.
According to this page it seems to be a better solution to use Date's "toLocaleTimeString" method.
Another way - from an ISO 8601 date.
var timestamp = 1293683278;
var date = new Date(timestamp * 1000);
var iso = date.toISOString().match(/(\d{2}:\d{2}:\d{2})/)
alert(iso[1]);
Based on #shomrat's answer, here is a snippet that automatically writes datetime like this (a bit similar to StackOverflow's date for answers: answered Nov 6 '16 at 11:51):
today, 11:23
or
yersterday, 11:23
or (if different but same year than today)
6 Nov, 11:23
or (if another year than today)
6 Nov 2016, 11:23
function timeConverter(t) {
var a = new Date(t * 1000);
var today = new Date();
var yesterday = new Date(Date.now() - 86400000);
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
var year = a.getFullYear();
var month = months[a.getMonth()];
var date = a.getDate();
var hour = a.getHours();
var min = a.getMinutes();
if (a.setHours(0,0,0,0) == today.setHours(0,0,0,0))
return 'today, ' + hour + ':' + min;
else if (a.setHours(0,0,0,0) == yesterday.setHours(0,0,0,0))
return 'yesterday, ' + hour + ':' + min;
else if (year == today.getFullYear())
return date + ' ' + month + ', ' + hour + ':' + min;
else
return date + ' ' + month + ' ' + year + ', ' + hour + ':' + min;
}
function getTIMESTAMP() {
var date = new Date();
var year = date.getFullYear();
var month = ("0" + (date.getMonth() + 1)).substr(-2);
var day = ("0" + date.getDate()).substr(-2);
var hour = ("0" + date.getHours()).substr(-2);
var minutes = ("0" + date.getMinutes()).substr(-2);
var seconds = ("0" + date.getSeconds()).substr(-2);
return year + "-" + month + "-" + day + " " + hour + ":" + minutes + ":" + seconds;
}
//2016-01-14 02:40:01
The modern solution that doesn't need a 40 KB library:
Intl.DateTimeFormat is the non-culturally imperialistic way to format a date/time.
// Setup once
var options = {
//weekday: 'long',
//month: 'short',
//year: 'numeric',
//day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric'
},
intlDate = new Intl.DateTimeFormat( undefined, options );
// Reusable formatter
var timeStamp = 1412743273;
console.log( intlDate.format( new Date( 1000 * timeStamp ) ) );
Pay attention to the zero problem with some of the answers. For example, the timestamp 1439329773 would be mistakenly converted to 12/08/2015 0:49.
I would suggest on using the following to overcome this issue:
var timestamp = 1439329773; // replace your timestamp
var date = new Date(timestamp * 1000);
var formattedDate = ('0' + date.getDate()).slice(-2) + '/' + ('0' + (date.getMonth() + 1)).slice(-2) + '/' + date.getFullYear() + ' ' + ('0' + date.getHours()).slice(-2) + ':' + ('0' + date.getMinutes()).slice(-2);
console.log(formattedDate);
Now results in:
12/08/2015 00:49
There are multiple ways to convert unix timestamp to time (HH/MM/SS)
Using new Date() - this is in-built in javascript
moment package - this is a famous node module, but this is going to deprecate.
dayjs package - this is one of the latest and fast growing node module
Using new Date()
const dateTimeStr = new Date(1504052527183).toLocaleString()
const result = (dateTimeStr.split(", ")[1]).split(":").join("/")
console.log(result)
Using moment
const moment = require('moment')
const timestampObj = moment.unix(1504052527183);
const result = timestampObj.format("HH/mm/ss")
console.log(result);
Using day.js
const dayjs = require('dayjs')
const result = dayjs(1504052527183).format("HH/mm/ss")
console.log(result);
you can check the timestamp to time conversion with an online time conversion tool
// Format value as two digits 0 => 00, 1 => 01
function twoDigits(value) {
if(value < 10) {
return '0' + value;
}
return value;
}
var date = new Date(unix_timestamp*1000);
// display in format HH:MM:SS
var formattedTime = twoDigits(date.getHours())
+ ':' + twoDigits(date.getMinutes())
+ ':' + twoDigits(date.getSeconds());
function getDateTimeFromTimestamp(unixTimeStamp) {
let date = new Date(unixTimeStamp);
return ('0' + date.getDate()).slice(-2) + '/' + ('0' + (date.getMonth() + 1)).slice(-2) + '/' + date.getFullYear() + ' ' + ('0' + date.getHours()).slice(-2) + ':' + ('0' + date.getMinutes()).slice(-2);
}
const myTime = getDateTimeFromTimestamp(1435986900000);
console.log(myTime); // output 01/05/2000 11:00
You can use the following function to convert your timestamp to HH:MM:SS format :
var convertTime = function(timestamp, separator) {
var pad = function(input) {return input < 10 ? "0" + input : input;};
var date = timestamp ? new Date(timestamp * 1000) : new Date();
return [
pad(date.getHours()),
pad(date.getMinutes()),
pad(date.getSeconds())
].join(typeof separator !== 'undefined' ? separator : ':' );
}
Without passing a separator, it uses : as the (default) separator :
time = convertTime(1061351153); // --> OUTPUT = 05:45:53
If you want to use / as a separator, just pass it as the second parameter:
time = convertTime(920535115, '/'); // --> OUTPUT = 09/11/55
Demo
var convertTime = function(timestamp, separator) {
var pad = function(input) {return input < 10 ? "0" + input : input;};
var date = timestamp ? new Date(timestamp * 1000) : new Date();
return [
pad(date.getHours()),
pad(date.getMinutes()),
pad(date.getSeconds())
].join(typeof separator !== 'undefined' ? separator : ':' );
}
document.body.innerHTML = '<pre>' + JSON.stringify({
920535115 : convertTime(920535115, '/'),
1061351153 : convertTime(1061351153, ':'),
1435651350 : convertTime(1435651350, '-'),
1487938926 : convertTime(1487938926),
1555135551 : convertTime(1555135551, '.')
}, null, '\t') + '</pre>';
See also this Fiddle.
function timeConverter(UNIX_timestamp){
var a = new Date(UNIX_timestamp*1000);
var hour = a.getUTCHours();
var min = a.getUTCMinutes();
var sec = a.getUTCSeconds();
var time = hour+':'+min+':'+sec ;
return time;
}
See Date/Epoch Converter.
You need to ParseInt, otherwise it wouldn't work:
if (!window.a)
window.a = new Date();
var mEpoch = parseInt(UNIX_timestamp);
if (mEpoch < 10000000000)
mEpoch *= 1000;
------
a.setTime(mEpoch);
var year = a.getFullYear();
...
return time;
Shortest
(new Date(ts*1000)+'').slice(16,24)
let ts = 1549312452;
let time = (new Date(ts*1000)+'').slice(16,24);
console.log(time);
Try this :
new Date(1638525320* 1e3).toISOString() //2021-12-03T09:55:20.000Z
function getDateTime(unixTimeStamp) {
var d = new Date(unixTimeStamp);
var h = (d.getHours().toString().length == 1) ? ('0' + d.getHours()) : d.getHours();
var m = (d.getMinutes().toString().length == 1) ? ('0' + d.getMinutes()) : d.getMinutes();
var s = (d.getSeconds().toString().length == 1) ? ('0' + d.getSeconds()) : d.getSeconds();
var time = h + '/' + m + '/' + s;
return time;
}
var myTime = getDateTime(1435986900000);
console.log(myTime); // output 01/15/00
moment.js
convert timestamps to date string in js
https://momentjs.com/
moment().format('YYYY-MM-DD hh:mm:ss');
// "2020-01-10 11:55:43"
moment(1578478211000).format('YYYY-MM-DD hh:mm:ss');
// "2020-01-08 06:10:11"
If you want to convert Unix time duration to real hours, minutes, and seconds, you could use the following code:
var hours = Math.floor(timestamp / 60 / 60);
var minutes = Math.floor((timestamp - hours * 60 * 60) / 60);
var seconds = Math.floor(timestamp - hours * 60 * 60 - minutes * 60 );
var duration = hours + ':' + minutes + ':' + seconds;
Code below also provides 3-digit millisecs, ideal for console log prefixes:
const timeStrGet = date => {
const milliSecsStr = date.getMilliseconds().toString().padStart(3, '0') ;
return `${date.toLocaleTimeString('it-US')}.${milliSecsStr}`;
};
setInterval(() => console.log(timeStrGet(new Date())), 299);

combine date and time into a single datetime [duplicate]

This question already has answers here:
Combine date and time string into single date with javascript
(8 answers)
Closed 3 years ago.
I have a date and time control, which I would like to concatenate
var startDate = jQuery('#startDatepicker').find("input").val();
var startTime = jQuery('#startTimepicker').find("input").val();
I have another var field which has data as below:
var targetTime = new Date().setMinutes(-5).valueOf();
startDatepicker has the value as : 02/06/2017
startTimepicker, currentTime has the value as : 05:17 am
targetTime has the value as: 1486374940591
I want to concatenate startdate and starttime in the format of targetTime. How to concatenate the start date and start time?
Thanks
This do what you need
var date = new Date(startDate + ' ' + startTime);
jQuery('#startDatepicker, #startTimepicker').on('input', function() {
var startDate = jQuery('#startDatepicker').val();
var startTime = jQuery('#startTimepicker').val();
var date = new Date(startDate + ' ' + startTime);
console.log(date)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Date
<input id="startDatepicker">Time
<input id="startTimepicker">
Pass your date and time to this function. It will return the Date object. Use getTime() on that to get the desired result. Codepen example.
function getAsDate(day, time)
{
var hours = Number(time.match(/^(\d+)/)[1]);
var minutes = Number(time.match(/:(\d+)/)[1]);
var AMPM = time.match(/\s(.*)$/)[1];
if(AMPM == "pm" && hours<12) hours = hours+12;
if(AMPM == "am" && hours==12) hours = hours-12;
var sHours = hours.toString();
var sMinutes = minutes.toString();
if(hours<10) sHours = "0" + sHours;
if(minutes<10) sMinutes = "0" + sMinutes;
time = sHours + ":" + sMinutes + ":00";
var d = new Date(day);
var n = d.toISOString().substring(0,10);
var newDate = new Date(n+"T"+time);
return newDate;
}

Get time from datetime format

I'm getting this date format from back-end: 1970-01-01T10:59:00Z
How can I get the time from it with JavaScript and put it in this input:
<input type="time" ng-model='content.time' />
Thanks for your help!
You could use the getHours(), getMinutes() and getSeconds() function and concatenate the values.
var result = document.getElementById("result");
var dateTime = new Date();
var hours = new Date().getHours();
var minutes = new Date().getMinutes();
var seconds = new Date().getSeconds();
result.innerHTML = hours + ":" + minutes + ":" + seconds;
<p id="result"></p>
var date = new Date($scope.content.time);
var converted = date.getHours() + ":" + date.getMinutes();
console.log(converted);
This might help you:
var dt = new Date();
var tm = dt.getUTCHours();
For UTC.
Also you can use:
new dt.getHours()
new dt.getMinutes()
var date = new Date("1970-01-01T10:59:00Z");
var converted = date.toLocaleString();
console.log(converted);
Then you'd just assign the converted value to the model.
With angular, and not just vanilla javascript/DOM manipulation, in your controller js:
var dateTime=<referenceToDataRetrievedFromBackEnd>;
/*Format the date you've retrieved*/
var hours = new Date().getHours();
var minutes = new Date().getMinutes();
var seconds = new Date().getSeconds();
var formattedTimeString=hours + ":" + minutes + ":" + seconds
/*This is the part that actual ties the retrieved and reformatted data to the view*/
$scope.content.time=formattedTimeString;
In your controller add this function
var parseDateTime = function (input) {
vars = input.split('T');
date = vars[0].split('-');
time = vars[1].split(':');
//return date in 'yyyy-MM-dd H:i:s'
return date[0] + '-' + date[1] + '-' + date[2] + ' ' + time[0] + ':' + time[1] + ':00';
}
Then you can use it with your datetime
var dateTime = DATE_RECEIVED_FROM_BACKEND;
$scope.content.time = parseDateTime(dateTime);
Hope this helps :)
place this code in the controller where after the data u receive from backend
var d = new Date("1970-01-01T10:59:09Z");//pass the object which have ur date
$scope.content.time=d.getHours() + ":" + d.getMinutes()+":"+ d.getSeconds();

Getting current date and time in JavaScript

I have a script that prints the current date and time in JavaScript, but the DATE is always wrong. Here is the code:
var currentdate = new Date();
var datetime = "Last Sync: " + currentdate.getDay() + "/" + currentdate.getMonth()
+ "/" + currentdate.getFullYear() + " # "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":" + currentdate.getSeconds();
It should print 18/04/2012 15:07:33 and prints 3/3/2012 15:07:33
.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();
To get time and date you should use
new Date().toLocaleString();
>> "09/08/2014, 2:35:56 AM"
To get only the date you should use
new Date().toLocaleDateString();
>> "09/08/2014"
To get only the time you should use
new Date().toLocaleTimeString();
>> "2:35:56 AM"
Or if you just want the time in the format hh:mm without AM/PM for US English
new Date().toLocaleTimeString('en-US', { hour12: false,
hour: "numeric",
minute: "numeric"});
>> "02:35"
or for British English
new Date().toLocaleTimeString('en-GB', { hour: "numeric",
minute: "numeric"});
>> "02:35"
Read more here.
For true mysql style output use this function below: 2019/02/28 15:33:12
If you click the 'Run code snippet' button below
It will show you an simple realtime digital clock example
The demo will appear below the code snippet.
function getDateTime() {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth()+1;
var day = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
if(month.toString().length == 1) {
month = '0'+month;
}
if(day.toString().length == 1) {
day = '0'+day;
}
if(hour.toString().length == 1) {
hour = '0'+hour;
}
if(minute.toString().length == 1) {
minute = '0'+minute;
}
if(second.toString().length == 1) {
second = '0'+second;
}
var dateTime = year+'/'+month+'/'+day+' '+hour+':'+minute+':'+second;
return dateTime;
}
// example usage: realtime clock
setInterval(function(){
currentTime = getDateTime();
document.getElementById("digital-clock").innerHTML = currentTime;
}, 1000);
<div id="digital-clock"></div>
Just use:
var d = new Date();
document.write(d.toLocaleString());
document.write("<br>");
Short
I develop Steve answer to get exactly what OP need
new Date().toLocaleString().replace(',','')
console.log(new Date().toLocaleString().replace(',',''));
var currentdate = new Date();
var datetime = "Last Sync: " + currentdate.getDate() + "/"+(currentdate.getMonth()+1)
+ "/" + currentdate.getFullYear() + " # "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":" + currentdate.getSeconds();
Change .getDay() method to .GetDate() and add one to month, because it counts months from 0.
This should do the trick:
function dateToString(date) {
var month = date.getMonth() + 1;
var day = date.getDate();
var dateOfString = (("" + day).length < 2 ? "0" : "") + day + "/";
dateOfString += (("" + month).length < 2 ? "0" : "") + month + "/";
dateOfString += date.getFullYear();
return dateOfString;
}
var currentdate = new Date();
var datetime = "Last Sync: ";
datetime += dateToString(currentdate );
datetime += + currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();
Basic JS (good to learn): we use the Date() function and do all that we need to show the date and day in our custom format.
var myDate = new Date();
let daysList = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
let monthsList = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Aug', 'Oct', 'Nov', 'Dec'];
let date = myDate.getDate();
let month = monthsList[myDate.getMonth()];
let year = myDate.getFullYear();
let day = daysList[myDate.getDay()];
let today = `${date} ${month} ${year}, ${day}`;
let amOrPm;
let twelveHours = function (){
if(myDate.getHours() > 12)
{
amOrPm = 'PM';
let twentyFourHourTime = myDate.getHours();
let conversion = twentyFourHourTime - 12;
return `${conversion}`
}else {
amOrPm = 'AM';
return `${myDate.getHours()}`}
};
let hours = twelveHours();
let minutes = myDate.getMinutes();
let currentTime = `${hours}:${minutes} ${amOrPm}`;
console.log(today + ' ' + currentTime);
Node JS (quick & easy): Install the npm pagckage using (npm install date-and-time), then run the below.
let nodeDate = require('date-and-time');
let now = nodeDate.format(new Date(), 'DD-MMMM-YYYY, hh:mm:ss a');
console.log(now);
Short and simple:-
console.log(new Date().toLocaleString());
Reference
I have found the simplest way to get current date and time in JavaScript from here - How to get current Date and Time using JavaScript
var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var CurrentDateTime = date+' '+time;
getDay() gets the day of the week. 3 is Wednesday. You want getDate(), that will return 18.
Also getMonth() starts at 0, you need to add 1 to get 4 (April).
DEMO: http://jsfiddle.net/4zVxp/
You need to use getDate() to get the date part. The getDay() function returns the day number (Sunday = 0, Monday = 1...), and the getMonth() returns a 0 based index, so you need to increment it by 1.
var currentdate = new Date();
var datetime = "Last Sync: " + currentdate.getDate() + "/"+ (parseInt(currentdate.getMonth()) + 1)
+ "/" + currentdate.getFullYear() + " # "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":" + currentdate.getSeconds();
const date = new Date()
console.log(date.toLocaleTimeString("en-us", {timeStyle: "medium"})) // Only Time
console.log(date.toLocaleString()) // For both Date and Time
For Documentation
function getTimeStamp() {
var now = new Date();
return ((now.getMonth() + 1) + '/' + (now.getDate()) + '/' + now.getFullYear() + " " + now.getHours() + ':'
+ ((now.getMinutes() < 10) ? ("0" + now.getMinutes()) : (now.getMinutes())) + ':' + ((now.getSeconds() < 10) ? ("0" + now
.getSeconds()) : (now.getSeconds())));
}
get current date and time
var now = new Date();
var datetime = now.getFullYear()+'/'+(now.getMonth()+1)+'/'+now.getDate();
datetime += ' '+now.getHours()+':'+now.getMinutes()+':'+now.getSeconds();
This question is quite old and the answers are too. Instead of those monstrous functions, we now can use moment.js to get the current date, which actually makes it very easy. All that has to be done is including moment.js in our project and get a well formated date, for example, by:
moment().format("dddd, MMMM Do YYYY, h:mm:ss a");
I think that makes it way easier to handle dates in javascript.
.getDay returns day of week. You need .getDate instead.
.getMonth returns values from 0 to 11. You'll need to add 1 to the result to get "human" month number.
This little code is easy and works everywhere.
<p id="dnt"></p>
<script>
document.getElementById("dnt").innerHTML = Date();
</script>
there is room to design
function UniqueDateTime(format='',language='en-US'){
//returns a meaningful unique number based on current time, and milliseconds, making it virtually unique
//e.g : 20170428-115833-547
//allows personal formatting like more usual :YYYYMMDDHHmmSS, or YYYYMMDD_HH:mm:SS
var dt = new Date();
var modele="YYYYMMDD-HHmmSS-mss";
if (format!==''){
modele=format;
}
modele=modele.replace("YYYY",dt.getFullYear());
modele=modele.replace("MM",(dt.getMonth()+1).toLocaleString(language, {minimumIntegerDigits: 2, useGrouping:false}));
modele=modele.replace("DD",dt.getDate().toLocaleString(language, {minimumIntegerDigits: 2, useGrouping:false}));
modele=modele.replace("HH",dt.getHours().toLocaleString(language, {minimumIntegerDigits: 2, useGrouping:false}));
modele=modele.replace("mm",dt.getMinutes().toLocaleString(language, {minimumIntegerDigits: 2, useGrouping:false}));
modele=modele.replace("SS",dt.getSeconds().toLocaleString(language, {minimumIntegerDigits: 2, useGrouping:false}));
modele=modele.replace("mss",dt.getMilliseconds().toLocaleString(language, {minimumIntegerDigits: 3, useGrouping:false}));
return modele;
}
dt= new Date();
alert(dt.toISOString().substring(8,10) + "/" +
dt.toISOString().substring(5,7)+ "/" +
dt.toISOString().substring(0,4) + " " +
dt.toTimeString().substring(0,8))
var datetime = new Date().toLocaleString().slice(0,9) +" "+new Date(new Date()).toString().split(' ')[4];
console.log(datetime);
I think i am very late to share my answer, but i think it will be worth.
function __getCurrentDateTime(format){
var dt=new Date(),x,date=[];
date['d']=dt.getDate();
date['dd']=dt.getDate()>10?dt.getDate():'0'+dt.getDate();
date['m']=dt.getMonth()+1;
date['mm']=(dt.getMonth()+1)>10?(dt.getMonth()+1):'0'+(dt.getMonth()+1);
date['yyyy']=dt.getFullYear();
date['yy']=dt.getFullYear().toString().slice(-2);
date['h']=(dt.getHours()>12?dt.getHours()-12:dt.getHours());
date['hh']=dt.getHours();
date['mi']=dt.getMinutes();
date['mimi']=dt.getMinutes()<10?('0'+dt.getMinutes()):dt.getMinutes();
date['s']=dt.getSeconds();
date['ss']=dt.getSeconds()<10?('0'+dt.getSeconds()):dt.getSeconds();
date['sss']=dt.getMilliseconds();
date['ampm']=(dt.getHours()>=12?'PM':'AM');
x=format.toLowerCase();
x=x.indexOf('dd')!=-1?x.replace(/(dd)/i,date['dd']):x.replace(/(d)/i,date['d']);
x=x.indexOf('mm')!=-1?x.replace(/(mm)/i,date['mm']):x.replace(/(m)/i,date['m']);
x=x.indexOf('yyyy')!=-1?x.replace(/(yyyy)/i,date['yyyy']):x.replace(/(yy)/i,date['yy']);
x=x.indexOf('hh')!=-1?x.replace(/(hh)/i,date['hh']):x.replace(/(h)/i,date['h']);
x=x.indexOf('mimi')!=-1?x.replace(/(mimi)/i,date['mimi']):x.replace(/(mi)/i,date['mi']);
if(x.indexOf('sss')!=-1){ x=x.replace(/(sss)/i,date['sss']); }
x=x.indexOf('ss')!=-1?x.replace(/(ss)/i,date['ss']):x.replace(/(s)/i,date['s']);
if(x.indexOf('ampm')!=-1){ x=x.replace(/(ampm)/i,date['ampm']); }
return x;
}
console.log(__getCurrentDateTime()); //returns in dd-mm-yyyy HH:MM:SS
console.log(__getCurrentDateTime('dd-mm-yyyy')); //return in 05-12-2016
console.log(__getCurrentDateTime('dd/mm*yyyy')); //return in 05/12*2016
console.log(__getCurrentDateTime('hh:mimi:ss')); //return in 13:05:30
console.log(__getCurrentDateTime('h:mi:ss ampm')); //return in 1:5:30 PM
I needed to figure this out for a slate in after effects. Here's what I came up with after taking elements from a few different sources -- Formatting is MM/DD/YYYY HH:MM AM/PM
D = new Date(Date(00));
M = D.getMonth()+1;
H = D.getHours();
Mi = D.getMinutes();
N = "AM"
if (H >= 12)
N = "PM"
if (H > 12)
{
H = H-12
}
amtOfZeroes = 2;
isNeg = false;
if (M < 0)
{
M = Math.abs(M);
isNeg = true;
}
Mo = Math.round(M) + "";
while(Mo.length < amtOfZeroes)
{
Mo = "0" + Mo;
}
if (isNeg)
Mo = "-" + Mo;
if (H < 0)
{
H = Math.abs(H);
isNeg = true;
}
Ho = Math.round(H) + "";
while(Ho.length < amtOfZeroes)
{
Ho = "0" + Ho;
}
if (isNeg)
Ho = "-" + Ho;
if (Mi < 0)
{
Mi = Math.abs(Mi);
isNeg = true;
}
Min = Math.round(Mi) + "";
while(Min.length < amtOfZeroes)
{
Min = "0" + Min;
}
if (isNeg)
Min = "-" + Min;
T = Ho + ":" + (Min)
Mo + "/" + D.getDate() + "/" + D.getFullYear() + " " + T + " " + N
If someone is in search of function
console.log(formatAMPM());
function formatAMPM() {
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
var ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
return strTime = date.getMonth() + '/' + date.getDay()+'/'+date.getFullYear()+' '+ hours + ':' + minutes +':'+ seconds + " " +ampm;
}
function display_c(){
var refresh = 1000; // Refresh rate in milli seconds
mytime = setTimeout('display_ct()', refresh)
}
function display_ct() {
var strcount
var currentdate = new Date();
document.getElementById('ct').innerHTML = currentdate.toDateString() + " " + currentdate.getHours() + ":" + currentdate.getMinutes() + ":" + currentdate.getSeconds();
tt = display_c();
}
id = 'ct' // Replace in Your id
onload = "display_ct();" // Type inside a Body Tag
My well intended answer is to use this tiny bit of JS: https://github.com/rhroyston/clock-js
clock.now --> 1462248501241
clock.time --> 11:08 PM
clock.weekday --> monday
clock.day --> 2
clock.month --> may
clock.year --> 2016
clock.since(1462245888784) --> 44 minutes
clock.until(1462255888784) --> 2 hours
clock.what.time(1462245888784) --> 10:24 PM
clock.what.weekday(1461968554458) --> friday
clock.what.day('14622458887 84') --> 2
clock.what.month(1461968554458) --> april
clock.what.year('1461968554458') --> 2016
clock.what.time() --> 11:11 PM
clock.what.weekday('14619685abcd') --> clock.js error : expected unix timestamp as argument
clock.unit.seconds --> 1000
clock.unit.minutes --> 60000
clock.unit.hours --> 3600000
clock.unit.days --> 86400000
clock.unit.weeks --> 604800000
clock.unit.months --> 2628002880
clock.unit.years --> 31536000000
Its simple and superb
$(document).ready(function () {
var fpsOut = document.getElementById('myTime');
setInterval(function () {
var d = new Date();
fpsOut.innerHTML = d;
}, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myTime"></div>
please find the below fiddler for the example
http://jsfiddle.net/4zVxp/483/
Here is my work around clock full format with day, date, year and time
and make Sure the date of your PC is set to the right date and if you are using PHP make sure in php.ini date.timezone= xx where xx your current timezone
function startTime()
{
var today=new Date();
// 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
var suffixes = ['','st','nd','rd','th','th','th','th','th','th','th','th','th','th','th','th','th','th','th','th','th','st','nd','rd','th','th','th','th','th','th','th','st','nd','rd'];
var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var month = new Array(12);
month[0] = "January";
month[1] = "February";
month[2] = "March";
month[3] = "April";
month[4] = "May";
month[5] = "June";
month[6] = "July";
month[7] = "August";
month[8] = "September";
month[9] = "October";
month[10] = "November";
month[11] = "December";
document.getElementById('txt').innerHTML=(weekday[today.getDay()] + ',' + " " + today.getDate()+'<sup>'+suffixes[today.getDate()]+'</sup>' + ' of' + " " + month[today.getMonth()] + " " + today.getFullYear() + ' Time Now ' + today.toLocaleTimeString());
t=setTimeout(function(){startTime()},500);
}
<style>
sup {
vertical-align: super;
font-size: smaller;
}
</style>
<html>
<body onload="startTime()">
<div id="txt"></div>
</body>
</html>
This example of UK Time Zone.. set offset for specific Time Zone.
Example : for India : +05:30 , UK : +1
function realUKTime() {
// create Date object for current location
var d = new Date();
offset ='+1';
// convert to msec
// subtract local time zone offset
// get UTC time in msec
var utc = d.getTime() + (d.getTimezoneOffset() * 60000);
// create new Date object for different city
// using supplied offset
var nd = new Date(utc + (3600000*offset));
// return time as a string
var s = nd.getSeconds();
var i = nd.getMinutes();
var h = nd.getHours();
var cDate = nd.getDate();
var m = nd.getUTCMonth();
var y = nd.getFullYear();
var newUkTime = nd.toDateString() + " "+ (Number(h)-1)+":"+i+':'+s
$("#realTime").html(newUkTime);
}
setInterval(realUKTime(),1000);
Output :: Mon Dec 27 2021 12:6:3
we can use :
new Date().toLocaleDateString() to fetch current date and
new Date().toLocaleTimeString() to fetch current time
Ex:
const date = new Date().toLocaleDateString();
const time = new Date().toLocaleTimeString();

Categories

Resources