How to covert a string to a date in Angular13?
For example:
str = '2022-06-09T22:00:00Z'; to a datetime mm/dd/yyyy --:-- --
If you are okay with using a library, I would recommend to use moment.js.
Here's a link!
Firstly, since we can not access the inbuilt functions from a string, we need to convert it to a date:
var date = new Date("2022-06-09T22:00:00Z")
Using moment.js:
moment.utc(d).format('MM/DD/YYYY HH:mm:ss') // -> 06/09/2022 22:00:00
Using standard in-built functions:
var formatted = ("0"+(d.getUTCMonth()+1)).slice(-2) + "/" + ("0" + d.getUTCDate()).slice(-2) + "/" + d.getUTCFullYear() + " " + ("0" + d.getUTCHours()).slice(-2) + ":" + ("0" + d.getUTCMinutes()).slice(-2) + ":" + ("0" + d.getUTCSeconds()).slice(-2);
If you don't want the time in UTC, you can simply puzzle it around to remove it.
new Date("2022-06-09T22:00:00Z")
You can use angular pipe date
<span>{{ str | date: 'mm/dd/yyyy h:mm:ss' }}</span>
StackBlitz
Related
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());
Is it possible to attach/include timezone abbreviation along with the timestamp value?. the below code returns the value something like this eg:2-16-2017 # 16:7:20
I would like to include timezone abbreviation into this value? any thoughts
var currentdate = new Date();
var datetime = (currentdate.getMonth()+1) + "-"
+ currentdate.getDate() + "-"
+ currentdate.getFullYear() + " # "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();alert(datetime)
Thanks,
Muthu
I don't know whether you can get timeZone abbreviations but definitely, you can get the offset.
var offset = new Date().getTimezoneOffset();
console.log(offset);
One more option is to use toTimeString() instead of manually concatenating the time part:
currentdate.toTimeString() //"01:19:10 GMT+0400 (SAMT)"
I got a function which converts my timestamp into a date and looks like this:
delivery: function(created) {
var date = new Date(created * 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);
return formattedDate;
}
now I want to display the date in MM/DD/YYYY for the american user which come to my site, so I would like to implement an if-clause, which firstly looks where the user comes from and then display the date in MM/DD/YYYY if he is from america, and if he is from europe in DD/MM/YYYY
Well in the SAPUI5 documentation I just saw this:
// The source value is given as timestamp. The used output pattern is "dd.MM.yyyy HH:mm": e.g. 22.12.2010 13:15
oType = new sap.ui.model.type.DateTime({source: {pattern: "timestamp"}, pattern: "dd.MMM.yyyy HH:mm"});
but I don't really understand how it works if I do oType.formatValue(created); its not working so maybe someone with more experience can explain me where I have to put my timestamp which is stored under "created"
What's wrong with simply using
delivery: function(created) {
var date = new Date(created * 1000);
return date.toLocaleDateString() + " " + date.toLocaleTimeString();
}
exactly?
EDIT: For clarity, I've supplied the whole function, not just the return statement
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;
}
}
I need to output the current UTC datetime as a string with the following format:
YYYY/mm/dd hh:m:sec
How do I achieve that with Javascript?
You can build it manually:
var m = new Date();
var dateString = m.getUTCFullYear() +"/"+ (m.getUTCMonth()+1) +"/"+ m.getUTCDate() + " " + m.getUTCHours() + ":" + m.getUTCMinutes() + ":" + m.getUTCSeconds();
and to force two digits on the values that require it, you can use something like this:
("0000" + 5).slice(-2)
Which would look like this:
var m = new Date();
var dateString =
m.getUTCFullYear() + "/" +
("0" + (m.getUTCMonth()+1)).slice(-2) + "/" +
("0" + m.getUTCDate()).slice(-2) + " " +
("0" + m.getUTCHours()).slice(-2) + ":" +
("0" + m.getUTCMinutes()).slice(-2) + ":" +
("0" + m.getUTCSeconds()).slice(-2);
console.log(dateString);
No library, one line, properly padded
const str = (new Date()).toISOString().slice(0, 19).replace(/-/g, "/").replace("T", " ");
It uses the built-in function Date.toISOString(), chops off the ms, replaces the hyphens with slashes, and replaces the T with a space to go from say '2019-01-05T09:01:07.123' to '2019/01/05 09:01:07'.
Local time instead of UTC
const now = new Date();
const offsetMs = now.getTimezoneOffset() * 60 * 1000;
const dateLocal = new Date(now.getTime() - offsetMs);
const str = dateLocal.toISOString().slice(0, 19).replace(/-/g, "/").replace("T", " ");
With jQuery date format :
$.format.date(new Date(), 'yyyy/MM/dd HH:mm:ss');
https://github.com/phstc/jquery-dateFormat
Enjoy
I wrote a simple library for manipulating the JavaScript date object. You can try this:
var dateString = timeSolver.getString(new Date(), "YYYY/MM/DD HH:MM:SS.SSS")
Library here:
https://github.com/sean1093/timeSolver
Not tested, but something like this:
var now = new Date();
var str = now.getUTCFullYear().toString() + "/" +
(now.getUTCMonth() + 1).toString() +
"/" + now.getUTCDate() + " " + now.getUTCHours() +
":" + now.getUTCMinutes() + ":" + now.getUTCSeconds();
Of course, you'll need to pad the hours, minutes, and seconds to two digits or you'll sometimes get weird looking times like "2011/12/2 19:2:8."
Alternative to answer of #JosephMarikle
If you do not want to figth against timezone UTC etc:
var dateString =
("0" + date.getUTCDate()).slice(-2) + "/" +
("0" + (date.getUTCMonth()+1)).slice(-2) + "/" +
date.getUTCFullYear() + " " +
//return HH:MM:SS with localtime without surprises
date.toLocaleTimeString()
console.log(fechaHoraActualCadena);
Posting another script solution DateX (author)
for anyone interested
DateX does NOT wrap the original Date object, but instead offers an identical interface with additional methods to format, localise, parse, diff and validate dates easily. So one can just do new DateX(..) instead of new Date(..) or use the lib as date utilities or even as wrapper or replacement around Date class.
The date format used is identical to php date format.
c-like format is also supported (although not fully)
for the example posted (YYYY/mm/dd hh:m:sec) the format to use would be Y/m/d H:i:s eg
var formatted_date = new DateX().format('Y/m/d H:i:s');
or
var formatted_now_date_gmt = new DateX(DateX.UTC()).format('Y/m/d H:i:s');
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/UTC