Get current date in this format [duplicate] - javascript

This question already has answers here:
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 6 years ago.
How can I get the current date in Javascript and format it this way "2015-03-25T12:00:00" ?
I would like to know if there is a function or method for this. I am not asking how to convert a string into another.

To be precise: .toISOString().slice(0, -5)
var d1 = new Date()
var str = d1.toISOString().slice(0, -5)
console.log(str);

How can I get the current date in Javascript and format it this way "2015-03-25T12:00:00" ?
That seems to be an ISO 8601 format date without a timezone, which will be treated as a "local" time. There is a built—in toISOString method, but it always uses UTC.
So you can either write your own function (fairly trivial, see below) or use a library (really not required if you just want to format a date string).
I would like to know if there is a function or method for this.
Not a built–in function, no.
/* Return an ISO 8601 string without timezone
** #param {Date} d - date to create string for
** #returns {string} string formatted as ISO 8601 without timezone
*/
function toISOStringLocal(d) {
function z(n){return (n<10?'0':'') + n}
return d.getFullYear() + '-' + z(d.getMonth()+1) + '-' +
z(d.getDate()) + 'T' + z(d.getHours()) + ':' +
z(d.getMinutes()) + ':' + z(d.getSeconds())
}
document.write(toISOStringLocal(new Date()));

Use moment.js It will blow your mind. Add this script to you HTML
<script type="text/javascript" src="http://momentjs.com/downloads/moment-with-locales.js"></script>
And use this code:
var date=moment().format('YYYY-MM-DDTHH:mm:ss');

Try this function:
function(d) {
var cad = "";
try{
cad = d.getUTCFullYear() + "-" + pad(d.getMonth() + 1) + "-" + pad(d.getUTCDate()) + "T" + pad(d.getHours())
+ ":" + pad(d.getUTCMinutes()) + ":" + pad( d.getSeconds()) ;
return cad;
}catch(e){
return null;
}
}

Related

Convert UTC to current timezone in javascript

I have time as 2023-02-01T17:00:22.127Z which is in UTC. I want to convert this to the timezone of the user from where user is logged in. How can I do this using javascript?
I was trying to use https://yarnpkg.com/package/jstz but couldn’t use a way to convert the time. Please help resolve this issue
Here is a function that converts a UTC date string to a local browser date string with format YYYY-MM-DD hh:MM:
function getLocalDateString(utcStr) {
const date = new Date(utcStr);
return date.getFullYear()
+ '-' + String(date.getMonth() + 1).padStart(2, '0')
+ '-' + String(date.getDate()).padStart(2, '0')
+ ' ' + String(date.getHours()).padStart(2, '0')
+ ':' + String(date.getMinutes()).padStart(2, '0');
}
console.log({
'2023-02-01T00:55:22.127Z': getLocalDateString('2023-02-01T00:55:22.127Z'),
'2023-02-01T17:00:22.127Z': getLocalDateString('2023-02-01T17:00:22.127Z')
});
Ouput in my timezone:
{
"2023-02-01T00:55:22.127Z": "2023-01-31 16:55",
"2023-02-01T17:00:22.127Z": "2023-02-01 09:00"
}

Convert stringDate to new Date() and back again in same format [duplicate]

This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 3 years ago.
I've got multiple dictionaries with dates in and I need to find the highest one. To compare the dates I get the date from the dictionary, convert it using new Date(dateString) to be able to compare the dates to get the latest date.
The dateString looks like this: 2019-03-07 08:40:16
I convert this using new Date(dateString) and it looks like this:
Thu Mar 07 2019 08:40:16 GMT+0000 (Greenwich Mean Time)
I then need to convert it back to original format YYYY-MM-DD HH:MM:SS
What is the best way to do this, I thought there would be something where you could define the output format for new Date() but can't find anything.
Any help is appreciated.
I'd recommend you to use Moment https://momentjs.com/ lib for time comparison and formatting.
const date1 = moment('2019-03-06 08:40:16', 'YYYY-MM-DD HH:mm:ss');
const date2 = moment('2019-03-07 08:40:16', 'YYYY-MM-DD HH:mm:ss');
const isBefore = date1.isBefore(date2);
console.log('isBefore', isBefore);
console.log('formatted date:', date2.format('YYYY-MM-DD HH:mm:ss'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
This is surely ain't the most elegant solution but based on the conversion from dateString, you can reconstruct it using the Date() objects built-in methods.
var dateString = "2019-03-07 08:40:16";
var temp = new Date(dateString);
var temp2 = "" + temp.getFullYear() + "-" + (temp.getMonth() + 1) + "-" + temp.getDate() + " " + temp.getHours() + ":" + temp.getMinutes() + ":" + temp.getSeconds();
console.log(temp2);
If you plan to do this with multiple dates, you might consider enhancing the Date object with your own method like:
Date.prototype.reformat = function() {
return this.getFullYear() + "-" + (this.getMonth() + 1) + "-" + this.getDate() + " " + this.getHours() + ":" + this.getMinutes() + "." + this.getSeconds();
}
var dateString = "2019-03-07 08:40:16";
var temp = new Date(dateString);
console.log(temp.reformat());

How to extract mm/dd/yyyy from ISO-8601 date format 2014-12-29T22:04:56.000Z in JavaScript? [duplicate]

This question already has answers here:
How can I format an ISO 8601 date to a more readable format, using Javascript? [duplicate]
(5 answers)
Closed 6 years ago.
I have this information: 2014-12-29T22:04:56.000Z
I would like to get the 2014-12-29 part of it in 12/29/2014 format.
How can I do it in javascript?
Thanks!
You could format the date like this to get your desired formatting.
var date = new Date("2014-12-29T22:04:56.000Z");
function pad(number) {
if (number < 10) {
return '0' + number;
}
return number;
}
function formatDate() {
return pad(date.getUTCMonth() + 1) +
'/' + pad(date.getUTCDate()) + '/' + date.getUTCFullYear();
}
console.log(formatDate())
You could do this using RegExp replace:
var ds = '2014-12-29T22:04:56.000Z';
console.log(ds.replace(/^(\d{4})-(\d\d)-(\d\d).+$/, '$2/$3/$1'));
Another approach would be using simple String.slice to get the required parts from the date string:
console.log(ds.slice(5, 7) + '/' + ds.slice(8, 10) + '/' + ds.slice(0, 4));
strMDY = strISO.substring(5, 7) + "/" + strISO.substring(8, 10) + "/" + strISO.substring(0, 4)
http://www.w3schools.com/jsref/jsref_substring.asp

Force browser to display all dates to specific timezone [duplicate]

This question already has answers here:
Convert date to another timezone in JavaScript
(34 answers)
How to initialize a JavaScript Date to a particular time zone
(20 answers)
Closed 9 years ago.
How can I force Browser to display all date objects to use Specific Timezone.Like passing Europe/London.Is there any way to do so??
Update
Here I want is that all Jquery Datepicker open date and time as per Specific Timezone instead of Client's Machine.
You can't "set" the timezone offset, it's a read only property that is based on system settings.
You can generate time and date values for any timezone offset by simply adding the client timezone offset, then adding whatever offset you want (note that javascript Date object's timezone offset has an opposite sense to the usual value, so you add both rather than subtracting one and adding the other).
e.g.
// Provide offsetInMintes to add to UTC to get required time,
// e.g. Nepal Standard Time is UTC +05:45 -> +345 minutes
function generateOffsetTime(offsetInMinutes) {
function z(n){return (n<10? '0' : '') + n;}
var d = new Date();
d.setMinutes(d.getMinutes() + d.getTimezoneOffset() + offsetInMinutes);
return [z(d.getHours()),z(d.getMinutes()),z(d.getSeconds())].join(':');
}
alert('The time in Nepal is ' + generateOffsetTime(345));
Edit
You could add your own methods to Date.prototype:
Date.prototype.setOffset = function(offsetInMinutes, offsetName) {
this._offsetInMinutes = offsetInMinutes;
this._offsetName = offsetName;
};
Date.prototype.getOffsetFullDate = (function() {
var months = ('January February March April May June July ' +
'August September October November December').split(' ');
var days = 'Sunday Monday Tuesday Wednesday Thursday Friday Saturday'.split(' ');
return function() {
var d = new Date(+this);
d.setMinutes(d.getMinutes() + d.getTimezoneOffset() + this._offsetInMinutes);
return days[d.getDay()] + ' ' + d.getDate() + ' ' + months[d.getMonth()] +
', ' + this.getFullYear();
}
}());
Date.prototype.getOffsetTime = (function() {
function z(n){return (n<10? '0' : '') + n;}
return function() {
var d = new Date(+this);
d.setMinutes(d.getMinutes() + d.getTimezoneOffset() + this._offsetInMinutes);
return z(d.getHours()) + ':' + z(d.getMinutes()) + ':' +
z(d.getSeconds()) + ' ' + this._offsetName;
}
}());
var d = new Date();
d.setOffset(345, 'NST')
console.log(d.getOffsetFullDate() + ' ' + d.getOffsetTime());
Note that this keeps the date object's original timevalue, it adjusts values as they are retrieved so the timezone can be changed to get different values for the same date object, so you could continue with:
d.setOffset(600, 'AEST');
console.log(d.getOffsetFullDate() + ' ' + d.getOffsetTime());
d.setOffset(630, 'LHI');
console.log(d.getOffsetFullDate() + ' ' + d.getOffsetTime());
But I still think it's better to build your own date constructor that leverages the built in Date rather than extends it.
Moment.js is a great library which could help you to achieve this.

Convert UTC value in dd-mm-yyyy format using javascript?

I want to convert UTC time value (e.g.1367214805) to date (in dd-mm-yyyy) format using javascript.
For e.g. in PHP if we use...
<?php Date("d-m-Y",'1367214805'); ?>
... we directly get the date in dd-mm-yyyy format.
Is there any such function in javascript?
- I tried Date() in various ways in javascript but every time it is printing the present date and time!!
Thanks
JavaScript uses millisecond epoch, so you need to multiply your number by 1000.
var t = 1367214805;
var d = new Date(t * 1000);
There are then .getUTCxxx methods to get the fields you want, and then you can just zero pad and concatenate to get the required string.
function epochToDate(t) {
function pad2(n) {
return n > 9 ? n : '0' + n;
}
var d = new Date(t * 1000);
var year = d.getUTCFullYear();
var month = d.getUTCMonth() + 1; // months start at zero
var day = d.getUTCDate();
return pad2(day) + '-' + pad2(month) + '-' + year;
}
Take a look at Moments.js, you should be able to get whatever format you want and easily.
console.log(new Date());
console.log(moment().format("D-M-YY"));
console.log(moment(1367214805 * 1000).format("DD-MM-YY"));
jsfiddle
You could use toISOString method and just ignore everything after the T e.g.
var isoDateStr = myDate.toISOString();
isoDateStr = isoDateStr.substring(0, isoDateStr.indexOf('T'));
This would give you standard UTC date format yyyy-mm-dd. If you need to specifically format the date as dd-mm-yyyy then you can take that result and switch the values i.e.
isoDateStr = isoDateStr.split('-').reverse().join('-');
You can try this:
myDate.toISOString().split('T')[0].split('-').reverse().join('-')
Why not use getUTCxxx() methods?
function formatUTC(time_UTC_in_milliseconds_since_epoch) {
/*
* author: WesternGun
*/
var time = new Date(time_UTC_in_milliseconds_since_epoch);
var formatted = time.getUTCFullYear() + "-"
+ (time.getUTCMonth() + 1).toString() + "-"
+ time.getUTCDate() + " "
+ time.getUTCHours() + ":"
+ time.getUTCMinutes() + ":"
+ time.getUTCSeconds();
return formatted;
}
Remember to add 1 to the month because the range of return value of getUTCMonth() is 0~11.
With your input, we have:
formatUTC(1367214805 * 1000); // return "2013-4-29 5:53:25"
To format the numbers into \d\d form, just create another function:
function normalizeNumber(input, toAdd) {
if (parseInt(input) < 10) {
return toAdd + input;
} else {
return input;
}
}
And use it like normalizeNumber((time.getUTCMonth() + 1).toString(), "0"), etc.

Categories