Convert SQL datetime to string or Date object [duplicate] - javascript

How can I convert a string to a date time object in javascript by specifying a format string?
I am looking for something like:
var dateTime = convertToDateTime("23.11.2009 12:34:56", "dd.MM.yyyy HH:mm:ss");

Use new Date(dateString) if your string is compatible with Date.parse(). If your format is incompatible (I think it is), you have to parse the string yourself (should be easy with regular expressions) and create a new Date object with explicit values for year, month, date, hour, minute and second.

I think this can help you: http://www.mattkruse.com/javascript/date/
There's a getDateFromFormat() function that you can tweak a little to solve your problem.
Update: there's an updated version of the samples available at javascripttoolbox.com

#Christoph Mentions using a regex to tackle the problem. Here's what I'm using:
var dateString = "2010-08-09 01:02:03";
var reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/;
var dateArray = reggie.exec(dateString);
var dateObject = new Date(
(+dateArray[1]),
(+dateArray[2])-1, // Careful, month starts at 0!
(+dateArray[3]),
(+dateArray[4]),
(+dateArray[5]),
(+dateArray[6])
);
It's by no means intelligent, just configure the regex and new Date(blah) to suit your needs.
Edit: Maybe a bit more understandable in ES6 using destructuring:
let dateString = "2010-08-09 01:02:03"
, reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/
, [, year, month, day, hours, minutes, seconds] = reggie.exec(dateString)
, dateObject = new Date(year, month-1, day, hours, minutes, seconds);
But in all honesty these days I reach for something like Moment

No sophisticated date/time formatting routines exist in JavaScript.
You will have to use an external library for formatted date output, "JavaScript Date Format" from Flagrant Badassery looks very promising.
For the input conversion, several suggestions have been made already. :)

Check out Moment.js. It is a modern and powerful library that makes up for JavaScript's woeful Date functions (or lack thereof).

Just for an updated answer here, there's a good js lib at http://www.datejs.com/
Datejs is an open source JavaScript Date library for parsing, formatting and processing.

var temp1 = "";
var temp2 = "";
var str1 = fd;
var str2 = td;
var dt1 = str1.substring(0,2);
var dt2 = str2.substring(0,2);
var mon1 = str1.substring(3,5);
var mon2 = str2.substring(3,5);
var yr1 = str1.substring(6,10);
var yr2 = str2.substring(6,10);
temp1 = mon1 + "/" + dt1 + "/" + yr1;
temp2 = mon2 + "/" + dt2 + "/" + yr2;
var cfd = Date.parse(temp1);
var ctd = Date.parse(temp2);
var date1 = new Date(cfd);
var date2 = new Date(ctd);
if(date1 > date2) {
alert("FROM DATE SHOULD BE MORE THAN TO DATE");
}

time = "2017-01-18T17:02:09.000+05:30"
t = new Date(time)
hr = ("0" + t.getHours()).slice(-2);
min = ("0" + t.getMinutes()).slice(-2);
sec = ("0" + t.getSeconds()).slice(-2);
t.getFullYear()+"-"+t.getMonth()+1+"-"+t.getDate()+" "+hr+":"+min+":"+sec

External library is an overkill for parsing one or two dates, so I made my own function using Oli's and Christoph's solutions. Here in central Europe we rarely use aything but the OP's format, so this should be enough for simple apps used here.
function ParseDate(dateString) {
//dd.mm.yyyy, or dd.mm.yy
var dateArr = dateString.split(".");
if (dateArr.length == 1) {
return null; //wrong format
}
//parse time after the year - separated by space
var spacePos = dateArr[2].indexOf(" ");
if(spacePos > 1) {
var timeString = dateArr[2].substr(spacePos + 1);
var timeArr = timeString.split(":");
dateArr[2] = dateArr[2].substr(0, spacePos);
if (timeArr.length == 2) {
//minutes only
return new Date(parseInt(dateArr[2]), parseInt(dateArr[1]-1), parseInt(dateArr[0]), parseInt(timeArr[0]), parseInt(timeArr[1]));
} else {
//including seconds
return new Date(parseInt(dateArr[2]), parseInt(dateArr[1]-1), parseInt(dateArr[0]), parseInt(timeArr[0]), parseInt(timeArr[1]), parseInt(timeArr[2]))
}
} else {
//gotcha at months - January is at 0, not 1 as one would expect
return new Date(parseInt(dateArr[2]), parseInt(dateArr[1] - 1), parseInt(dateArr[0]));
}
}

Date.parse() is fairly intelligent but I can't guarantee that format will parse correctly.
If it doesn't, you'd have to find something to bridge the two. Your example is pretty simple (being purely numbers) so a touch of REGEX (or even string.split() -- might be faster) paired with some parseInt() will allow you to quickly make a date.

Just to give my 5 cents.
My date format is dd.mm.yyyy (UK format) and none of the above examples were working for me. All the parsers were considering mm as day and dd as month.
I've found this library: http://joey.mazzarelli.com/2008/11/25/easy-date-parsing-with-javascript/
and it worked, because you can say the order of the fields like this:
>>console.log(new Date(Date.fromString('09.05.2012', {order: 'DMY'})));
Wed May 09 2012 00:00:00 GMT+0300 (EEST)
I hope that helps someone.

Moment.js will handle this:
var momentDate = moment('23.11.2009 12:34:56', 'DD.MM.YYYY HH:mm:ss');
var date = momentDate.;

You can use the moment.js library for this. I am using only to get time-specific output but you can select what kind of format you want to select.
Reference:
1. moment library: https://momentjs.com/
2. time and date specific functions: https://timestamp.online/article/how-to-convert-timestamp-to-datetime-in-javascript
convertDate(date) {
var momentDate = moment(date).format('hh : mm A');
return momentDate;
}
and you can call this method like:
this.convertDate('2020-05-01T10:31:18.837Z');
I hope it helps. Enjoy coding.

To fully satisfy the Date.parse convert string to format dd-mm-YYYY as specified in RFC822,
if you use yyyy-mm-dd parse may do a mistakes.

//Here pdate is the string date time
var date1=GetDate(pdate);
function GetDate(a){
var dateString = a.substr(6);
var currentTime = new Date(parseInt(dateString ));
var month =("0"+ (currentTime.getMonth() + 1)).slice(-2);
var day =("0"+ currentTime.getDate()).slice(-2);
var year = currentTime.getFullYear();
var date = day + "/" + month + "/" + year;
return date;
}

Related

Moment JS from yyyy-mm-ddthh:mm:ss to MM-DD-YY mm:ss [duplicate]

I want to parse the following string with moment.js 2014-02-27T10:00:00 and output
day month year (14 march 2014)
I have been reading the docs but without success
http://momentjs.com/docs/#/parsing/now/
I always seem to find myself landing here only to realize that the title and question are not quite aligned.
If you want a moment date from a string:
const myMomentObject = moment(str, 'YYYY-MM-DD')
From moment documentation:
Instead of modifying the native Date.prototype, Moment.js creates a wrapper for the Date object.
If you instead want a javascript Date object from a string:
const myDate = moment(str, 'YYYY-MM-DD').toDate();
You need to use the .format() function.
MM - Month number
MMM - Month word
var date = moment("2014-02-27T10:00:00").format('DD-MM-YYYY');
var dateMonthAsWord = moment("2014-02-27T10:00:00").format('DD-MMM-YYYY');
FIDDLE
No need for moment.js to parse the input since its format is the standard one :
var date = new Date('2014-02-27T10:00:00');
var formatted = moment(date).format('D MMMM YYYY');
http://es5.github.io/#x15.9.1.15
moment was perfect for what I needed. NOTE it ignores the hours and minutes and just does it's thing if you let it. This was perfect for me as my API call brings back the date and time but I only care about the date.
function momentTest() {
var varDate = "2018-01-19 18:05:01.423";
var myDate = moment(varDate,"YYYY-MM-DD").format("DD-MM-YYYY");
var todayDate = moment().format("DD-MM-YYYY");
var yesterdayDate = moment().subtract(1, 'days').format("DD-MM-YYYY");
var tomorrowDate = moment().add(1, 'days').format("DD-MM-YYYY");
alert(todayDate);
if (myDate == todayDate) {
alert("date is today");
} else if (myDate == yesterdayDate) {
alert("date is yesterday");
} else if (myDate == tomorrowDate) {
alert("date is tomorrow");
} else {
alert("It's not today, tomorrow or yesterday!");
}
}
How to change any string date to object date (also with moment.js):
let startDate = "2019-01-16T20:00:00.000";
let endDate = "2019-02-11T20:00:00.000";
let sDate = new Date(startDate);
let eDate = new Date(endDate);
with moment.js:
startDate = moment(sDate);
endDate = moment(eDate);
Maybe try the Intl polyfill for IE8 or the olyfill service ?
or
https://github.com/andyearnshaw/Intl.js/

Parse date in javascript issues

I get such date in javascript
var val = "1960-05-15T20:00:00"
But if I do
var date = new Date(val);
The data I get is one day later:
1960-05-16 // I use this to obtain it: Ext.Date.format(new Date(val), 'm/d/Y')
Can you help me how to parse this date? and get correct date with 1960-05-15?
Your date format is ISO 8601 represented as the local time with an offset to UTC appended.
The Ext.Date singleton support this format with the c flag.
var parsedDate = Ext.Date.parse('1960-05-15T20:00:00', 'c');
var dateStr = Ext.Date.format(parsedDate, 'Y-m-d');
// "1960-05-15"
Have a look at the Sencha ExtJs 6.2.1 documentation Ext.Date for further informations.
You can use native JS to accomplish the output of the Date object in to this format yyyy-mm-dd
Like so:
var val = '1960-05-15T20:00:00';
var d = new Date(val);
var date = d.getFullYear() + '-' + ('0' + (d.getMonth() + 1)).slice(-2) + '-' + ('0' + d.getDate()).slice(-2);
console.log(date);
When you do
var a = new Date(someDate)
variable a contains date according to your local timezone.
If you want date in same format as you entered , use toISOString method
var a = (new Date(someDate)).toISOString()
My recommendation would be, you can only assume the timezone from where the date is coming from. If you know exactly where that date is coming from, a.k.a London, New York, Sidney, etc... then you can use momentjs to set the UTC offset
var val = "1960-05-15T20:00:00"
// these are equivalent
moment(val).utcOffset("+08:00");
moment(val).utcOffset(8);
moment(val).utcOffset(480);
So the OP has said they're in
Tbilisi, Georgia GMT + 4.00
so
moment(val).utcOffset("+04:00");

Parse string to date with moment.js

I want to parse the following string with moment.js 2014-02-27T10:00:00 and output
day month year (14 march 2014)
I have been reading the docs but without success
http://momentjs.com/docs/#/parsing/now/
I always seem to find myself landing here only to realize that the title and question are not quite aligned.
If you want a moment date from a string:
const myMomentObject = moment(str, 'YYYY-MM-DD')
From moment documentation:
Instead of modifying the native Date.prototype, Moment.js creates a wrapper for the Date object.
If you instead want a javascript Date object from a string:
const myDate = moment(str, 'YYYY-MM-DD').toDate();
You need to use the .format() function.
MM - Month number
MMM - Month word
var date = moment("2014-02-27T10:00:00").format('DD-MM-YYYY');
var dateMonthAsWord = moment("2014-02-27T10:00:00").format('DD-MMM-YYYY');
FIDDLE
No need for moment.js to parse the input since its format is the standard one :
var date = new Date('2014-02-27T10:00:00');
var formatted = moment(date).format('D MMMM YYYY');
http://es5.github.io/#x15.9.1.15
moment was perfect for what I needed. NOTE it ignores the hours and minutes and just does it's thing if you let it. This was perfect for me as my API call brings back the date and time but I only care about the date.
function momentTest() {
var varDate = "2018-01-19 18:05:01.423";
var myDate = moment(varDate,"YYYY-MM-DD").format("DD-MM-YYYY");
var todayDate = moment().format("DD-MM-YYYY");
var yesterdayDate = moment().subtract(1, 'days').format("DD-MM-YYYY");
var tomorrowDate = moment().add(1, 'days').format("DD-MM-YYYY");
alert(todayDate);
if (myDate == todayDate) {
alert("date is today");
} else if (myDate == yesterdayDate) {
alert("date is yesterday");
} else if (myDate == tomorrowDate) {
alert("date is tomorrow");
} else {
alert("It's not today, tomorrow or yesterday!");
}
}
How to change any string date to object date (also with moment.js):
let startDate = "2019-01-16T20:00:00.000";
let endDate = "2019-02-11T20:00:00.000";
let sDate = new Date(startDate);
let eDate = new Date(endDate);
with moment.js:
startDate = moment(sDate);
endDate = moment(eDate);
Maybe try the Intl polyfill for IE8 or the olyfill service ?
or
https://github.com/andyearnshaw/Intl.js/

How to format a UTC date as a `YYYY-MM-DD hh:mm:ss` string using NodeJS?

Using NodeJS, I want to format a Date into the following string format:
var ts_hms = new Date(UTC);
ts_hms.format("%Y-%m-%d %H:%M:%S");
How do I do that?
If you're using Node.js, you're sure to have EcmaScript 5, and so Date has a toISOString method. You're asking for a slight modification of ISO8601:
new Date().toISOString()
> '2012-11-04T14:51:06.157Z'
So just cut a few things out, and you're set:
new Date().toISOString().
replace(/T/, ' '). // replace T with a space
replace(/\..+/, '') // delete the dot and everything after
> '2012-11-04 14:55:45'
Or, in one line: new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '')
ISO8601 is necessarily UTC (also indicated by the trailing Z on the first result), so you get UTC by default (always a good thing).
UPDATE 2021-10-06: Added Day.js and remove spurious edit by #ashleedawg
UPDATE 2021-04-07: Luxon added by #Tampa.
UPDATE 2021-02-28: It should now be noted that Moment.js is no longer being actively developed. It won't disappear in a hurry because it is embedded in so many other things. The website has some recommendations for alternatives and an explanation of why.
UPDATE 2017-03-29: Added date-fns, some notes on Moment and Datejs
UPDATE 2016-09-14: Added SugarJS which seems to have some excellent date/time functions.
OK, since no one has actually provided an actual answer, here is mine.
A library is certainly the best bet for handling dates and times in a standard way. There are lots of edge cases in date/time calculations so it is useful to be able to hand-off the development to a library.
Here is a list of the main Node compatible time formatting libraries:
Day.js [added 2021-10-06] "Fast 2kB alternative to Moment.js with the same modern API"
Luxon [added 2017-03-29, thanks to Tampa] "A powerful, modern, and friendly wrapper for JavaScript dates and times." - MomentJS rebuilt from the ground up with immutable types, chaining and much more.
Moment.js [thanks to Mustafa] "A lightweight (4.3k) javascript date library for parsing, manipulating, and formatting dates" - Includes internationalization, calculations and relative date formats - Update 2017-03-29: Not quite so light-weight any more but still the most comprehensive solution, especially if you need timezone support. - Update 2021-02-28: No longer in active development.
date-fns [added 2017-03-29, thanks to Fractalf] Small, fast, works with standard JS date objects. Great alternative to Moment if you don't need timezone support.
SugarJS - A general helper library adding much needed features to JavaScripts built-in object types. Includes some excellent looking date/time capabilities.
strftime - Just what it says, nice and simple
dateutil - This is the one I used to use before MomentJS
node-formatdate
TimeTraveller - "Time Traveller provides a set of utility methods to deal with dates. From adding and subtracting, to formatting. Time Traveller only extends date objects that it creates, without polluting the global namespace."
Tempus [thanks to Dan D] - UPDATE: this can also be used with Node and deployed with npm, see the docs
There are also non-Node libraries:
Datejs [thanks to Peter Olson] - not packaged in npm or GitHub so not quite so easy to use with Node - not really recommended as not updated since 2007!
There's a library for conversion:
npm install dateformat
Then write your requirement:
var dateFormat = require('dateformat');
Then bind the value:
var day=dateFormat(new Date(), "yyyy-mm-dd h:MM:ss");
see dateformat
I have nothing against libraries in general. In this case a general purpose library seems overkill, unless other parts of the application process dates heavily.
Writing small utility functions such as this is also a useful exercise for both beginning and accomplished programmers alike and can be a learning experience for the novices amongst us.
function dateFormat (date, fstr, utc) {
utc = utc ? 'getUTC' : 'get';
return fstr.replace (/%[YmdHMS]/g, function (m) {
switch (m) {
case '%Y': return date[utc + 'FullYear'] (); // no leading zeros required
case '%m': m = 1 + date[utc + 'Month'] (); break;
case '%d': m = date[utc + 'Date'] (); break;
case '%H': m = date[utc + 'Hours'] (); break;
case '%M': m = date[utc + 'Minutes'] (); break;
case '%S': m = date[utc + 'Seconds'] (); break;
default: return m.slice (1); // unknown code, remove %
}
// add leading zero if required
return ('0' + m).slice (-2);
});
}
/* dateFormat (new Date (), "%Y-%m-%d %H:%M:%S", true) returns
"2012-05-18 05:37:21" */
Check the code below and the link to Date Object, Intl.DateTimeFormat
// var ts_hms = new Date(UTC);
// ts_hms.format("%Y-%m-%d %H:%M:%S")
// exact format
console.log(new Date().toISOString().replace('T', ' ').substring(0, 19))
// other formats
console.log(new Date().toUTCString())
console.log(new Date().toLocaleString('en-US'))
console.log(new Date().toString())
// log format
const parts = new Date().toString().split(' ')
console.log([parts[1], parts[2], parts[4]].join(' '))
// intl
console.log(new Intl.DateTimeFormat('en-US', {dateStyle: 'long', timeStyle: 'long'}).format(new Date()))
Easily readable and customisable way to get a timestamp in your desired format, without use of any library:
function timestamp(){
function pad(n) {return n<10 ? "0"+n : n}
d=new Date()
dash="-"
colon=":"
return d.getFullYear()+dash+
pad(d.getMonth()+1)+dash+
pad(d.getDate())+" "+
pad(d.getHours())+colon+
pad(d.getMinutes())+colon+
pad(d.getSeconds())
}
(If you require time in UTC format, then just change the function calls. For example "getMonth" becomes "getUTCMonth")
The javascript library sugar.js (http://sugarjs.com/) has functions to format dates
Example:
Date.create().format('{dd}/{MM}/{yyyy} {hh}:{mm}:{ss}.{fff}')
I am using dateformat at Nodejs and angularjs, so good
install
$ npm install dateformat
$ dateformat --help
demo
var dateFormat = require('dateformat');
var now = new Date();
// Basic usage
dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT");
// Saturday, June 9th, 2007, 5:46:21 PM
// You can use one of several named masks
dateFormat(now, "isoDateTime");
// 2007-06-09T17:46:21
// ...Or add your own
dateFormat.masks.hammerTime = 'HH:MM! "Can\'t touch this!"';
dateFormat(now, "hammerTime");
// 17:46! Can't touch this!
// You can also provide the date as a string
dateFormat("Jun 9 2007", "fullDate");
// Saturday, June 9, 2007
...
Use the method provided in the Date object as follows:
var ts_hms = new Date();
console.log(
ts_hms.getFullYear() + '-' +
("0" + (ts_hms.getMonth() + 1)).slice(-2) + '-' +
("0" + (ts_hms.getDate())).slice(-2) + ' ' +
("0" + ts_hms.getHours()).slice(-2) + ':' +
("0" + ts_hms.getMinutes()).slice(-2) + ':' +
("0" + ts_hms.getSeconds()).slice(-2));
It looks really dirty, but it should work fine with JavaScript core methods
For date formatting the most easy way is using moment lib. https://momentjs.com/
const moment = require('moment')
const current = moment().utc().format('Y-M-D H:M:S')
Alternative #6233....
Add the UTC offset to the local time then convert it to the desired format with the toLocaleDateString() method of the Date object:
// Using the current date/time
let now_local = new Date();
let now_utc = new Date();
// Adding the UTC offset to create the UTC date/time
now_utc.setMinutes(now_utc.getMinutes() + now_utc.getTimezoneOffset())
// Specify the format you want
let date_format = {};
date_format.year = 'numeric';
date_format.month = 'numeric';
date_format.day = '2-digit';
date_format.hour = 'numeric';
date_format.minute = 'numeric';
date_format.second = 'numeric';
// Printing the date/time in UTC then local format
console.log('Date in UTC: ', now_utc.toLocaleDateString('us-EN', date_format));
console.log('Date in LOC: ', now_local.toLocaleDateString('us-EN', date_format));
I'm creating a date object defaulting to the local time. I'm adding the UTC off-set to it. I'm creating a date-formatting object. I'm displaying the UTC date/time in the desired format:
new Date(2015,1,3,15,30).toLocaleString()
//=> 2015-02-03 15:30:00
In reflect your time zone, you can use this
var datetime = new Date();
var dateString = new Date(
datetime.getTime() - datetime.getTimezoneOffset() * 60000
);
var curr_time = dateString.toISOString().replace("T", " ").substr(0, 19);
console.log(curr_time);
Here's a handy vanilla one-liner (adapted from this):
var timestamp =
new Date((dt = new Date()).getTime() - dt.getTimezoneOffset() * 60000)
.toISOString()
.replace(/(.*)T(.*)\..*/,'$1 $2')
console.log(timestamp)
Output: 2022-02-11 11:57:39
Use x-date module which is one of sub-modules of x-class library ;
require('x-date') ;
//---
new Date().format('yyyy-mm-dd HH:MM:ss')
//'2016-07-17 18:12:37'
new Date().format('ddd , yyyy-mm-dd HH:MM:ss')
// 'Sun , 2016-07-17 18:12:51'
new Date().format('dddd , yyyy-mm-dd HH:MM:ss')
//'Sunday , 2016-07-17 18:12:58'
new Date().format('dddd ddSS of mmm , yy')
// 'Sunday 17thth +0300f Jul , 16'
new Date().format('dddd ddS mmm , yy')
//'Sunday 17th Jul , 16'
I needed a simple formatting library without the bells and whistles of locale and language support. So I modified
http://www.mattkruse.com/javascript/date/date.js
and used it. See https://github.com/adgang/atom-time/blob/master/lib/dateformat.js
The documentation is pretty clear.
new Date().toString("yyyyMMddHHmmss").
replace(/T/, ' ').
replace(/\..+/, '')
with .toString(), This becomes in format
replace(/T/, ' '). //replace T to ' ' 2017-01-15T...
replace(/..+/, '') //for ...13:50:16.1271
example, see var date and hour:
var date="2017-01-15T13:50:16.1271".toString("yyyyMMddHHmmss").
replace(/T/, ' ').
replace(/\..+/, '');
var auxCopia=date.split(" ");
date=auxCopia[0];
var hour=auxCopia[1];
console.log(date);
console.log(hour);
Here's a lightweight library simple-date-format I've written, works both on node.js and in the browser
Install
Install with NPM
npm install #riversun/simple-date-format
or
Load directly(for browser),
<script src="https://cdn.jsdelivr.net/npm/#riversun/simple-date-format/lib/simple-date-format.js"></script>
Load Library
ES6
import SimpleDateFormat from "#riversun/simple-date-format";
CommonJS (node.js)
const SimpleDateFormat = require('#riversun/simple-date-format');
Usage1
const date = new Date('2018/07/17 12:08:56');
const sdf = new SimpleDateFormat();
console.log(sdf.formatWith("yyyy-MM-dd'T'HH:mm:ssXXX", date));//to be "2018-07-17T12:08:56+09:00"
Run on Pen
Usage2
const date = new Date('2018/07/17 12:08:56');
const sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
console.log(sdf.format(date));//to be "2018-07-17T12:08:56+09:00"
Patterns for formatting
https://github.com/riversun/simple-date-format#pattern-of-the-date
import dateFormat from 'dateformat';
var ano = new Date()
<footer>
<span>{props.data.footer_desc} <a href={props.data.footer_link}>{props.data.footer_text_link}</a> {" "}
({day = dateFormat(props.data.updatedAt, "yyyy")})
</span>
</footer>
rodape
Modern web browsers (and Node.js) expose internationalization and time zone support via the Intl object which offers a Intl.DateTimeFormat.prototype.formatToParts() method.
You can do below with no added library:
function format(dateObject){
let dtf = new Intl.DateTimeFormat("en-US", {
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric'
});
var parts = dtf.formatToParts(dateObject);
var fmtArr = ["year","month","day","hour","minute","second"];
var str = "";
for (var i = 0; i < fmtArr.length; i++) {
if(i===1 || i===2){
str += "-";
}
if(i===3){
str += " ";
}
if(i>=4){
str += ":";
}
for (var ii = 0; ii < parts.length; ii++) {
let type = parts[ii]["type"]
let value = parts[ii]["value"]
if(fmtArr[i]===type){
str = str += value;
}
}
}
return str;
}
console.log(format(Date.now()));
You can use Light-Weight library Moment js
npm install moment
Call the library
var moments = require("moment");
Now convert into your required format
moment().format('MMMM Do YYYY, h:mm:ss a');
And for more format and details, you can follow the official docs Moment js
I think this actually answers your question.
It is so annoying working with date/time in javascript.
After a few gray hairs I figured out that is was actually pretty simple.
var date = new Date();
var year = date.getUTCFullYear();
var month = date.getUTCMonth();
var day = date.getUTCDate();
var hours = date.getUTCHours();
var min = date.getUTCMinutes();
var sec = date.getUTCSeconds();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = ((hours + 11) % 12 + 1);//for 12 hour format
var str = month + "/" + day + "/" + year + " " + hours + ":" + min + ":" + sec + " " + ampm;
var now_utc = Date.UTC(str);
Here is a fiddle
appHelper.validateDates = function (start, end) {
var returnval = false;
var fd = new Date(start);
var fdms = fd.getTime();
var ed = new Date(end);
var edms = ed.getTime();
var cd = new Date();
var cdms = cd.getTime();
if (fdms >= edms) {
returnval = false;
console.log("step 1");
}
else if (cdms >= edms) {
returnval = false;
console.log("step 2");
}
else {
returnval = true;
console.log("step 3");
}
console.log("vall", returnval)
return returnval;
}
it's possible to solve this problem easily with 'Date'.
function getDateAndTime(time: Date) {
const date = time.toLocaleDateString('pt-BR', {
timeZone: 'America/Sao_Paulo',
});
const hour = time.toLocaleTimeString('pt-BR', {
timeZone: 'America/Sao_Paulo',
});
return `${date} ${hour}`;
}
it's to show: // 10/31/22 11:13:25

How can I convert string to datetime with format specification in JavaScript?

How can I convert a string to a date time object in javascript by specifying a format string?
I am looking for something like:
var dateTime = convertToDateTime("23.11.2009 12:34:56", "dd.MM.yyyy HH:mm:ss");
Use new Date(dateString) if your string is compatible with Date.parse(). If your format is incompatible (I think it is), you have to parse the string yourself (should be easy with regular expressions) and create a new Date object with explicit values for year, month, date, hour, minute and second.
I think this can help you: http://www.mattkruse.com/javascript/date/
There's a getDateFromFormat() function that you can tweak a little to solve your problem.
Update: there's an updated version of the samples available at javascripttoolbox.com
#Christoph Mentions using a regex to tackle the problem. Here's what I'm using:
var dateString = "2010-08-09 01:02:03";
var reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/;
var dateArray = reggie.exec(dateString);
var dateObject = new Date(
(+dateArray[1]),
(+dateArray[2])-1, // Careful, month starts at 0!
(+dateArray[3]),
(+dateArray[4]),
(+dateArray[5]),
(+dateArray[6])
);
It's by no means intelligent, just configure the regex and new Date(blah) to suit your needs.
Edit: Maybe a bit more understandable in ES6 using destructuring:
let dateString = "2010-08-09 01:02:03"
, reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/
, [, year, month, day, hours, minutes, seconds] = reggie.exec(dateString)
, dateObject = new Date(year, month-1, day, hours, minutes, seconds);
But in all honesty these days I reach for something like Moment
No sophisticated date/time formatting routines exist in JavaScript.
You will have to use an external library for formatted date output, "JavaScript Date Format" from Flagrant Badassery looks very promising.
For the input conversion, several suggestions have been made already. :)
Check out Moment.js. It is a modern and powerful library that makes up for JavaScript's woeful Date functions (or lack thereof).
Just for an updated answer here, there's a good js lib at http://www.datejs.com/
Datejs is an open source JavaScript Date library for parsing, formatting and processing.
var temp1 = "";
var temp2 = "";
var str1 = fd;
var str2 = td;
var dt1 = str1.substring(0,2);
var dt2 = str2.substring(0,2);
var mon1 = str1.substring(3,5);
var mon2 = str2.substring(3,5);
var yr1 = str1.substring(6,10);
var yr2 = str2.substring(6,10);
temp1 = mon1 + "/" + dt1 + "/" + yr1;
temp2 = mon2 + "/" + dt2 + "/" + yr2;
var cfd = Date.parse(temp1);
var ctd = Date.parse(temp2);
var date1 = new Date(cfd);
var date2 = new Date(ctd);
if(date1 > date2) {
alert("FROM DATE SHOULD BE MORE THAN TO DATE");
}
time = "2017-01-18T17:02:09.000+05:30"
t = new Date(time)
hr = ("0" + t.getHours()).slice(-2);
min = ("0" + t.getMinutes()).slice(-2);
sec = ("0" + t.getSeconds()).slice(-2);
t.getFullYear()+"-"+t.getMonth()+1+"-"+t.getDate()+" "+hr+":"+min+":"+sec
External library is an overkill for parsing one or two dates, so I made my own function using Oli's and Christoph's solutions. Here in central Europe we rarely use aything but the OP's format, so this should be enough for simple apps used here.
function ParseDate(dateString) {
//dd.mm.yyyy, or dd.mm.yy
var dateArr = dateString.split(".");
if (dateArr.length == 1) {
return null; //wrong format
}
//parse time after the year - separated by space
var spacePos = dateArr[2].indexOf(" ");
if(spacePos > 1) {
var timeString = dateArr[2].substr(spacePos + 1);
var timeArr = timeString.split(":");
dateArr[2] = dateArr[2].substr(0, spacePos);
if (timeArr.length == 2) {
//minutes only
return new Date(parseInt(dateArr[2]), parseInt(dateArr[1]-1), parseInt(dateArr[0]), parseInt(timeArr[0]), parseInt(timeArr[1]));
} else {
//including seconds
return new Date(parseInt(dateArr[2]), parseInt(dateArr[1]-1), parseInt(dateArr[0]), parseInt(timeArr[0]), parseInt(timeArr[1]), parseInt(timeArr[2]))
}
} else {
//gotcha at months - January is at 0, not 1 as one would expect
return new Date(parseInt(dateArr[2]), parseInt(dateArr[1] - 1), parseInt(dateArr[0]));
}
}
Date.parse() is fairly intelligent but I can't guarantee that format will parse correctly.
If it doesn't, you'd have to find something to bridge the two. Your example is pretty simple (being purely numbers) so a touch of REGEX (or even string.split() -- might be faster) paired with some parseInt() will allow you to quickly make a date.
Just to give my 5 cents.
My date format is dd.mm.yyyy (UK format) and none of the above examples were working for me. All the parsers were considering mm as day and dd as month.
I've found this library: http://joey.mazzarelli.com/2008/11/25/easy-date-parsing-with-javascript/
and it worked, because you can say the order of the fields like this:
>>console.log(new Date(Date.fromString('09.05.2012', {order: 'DMY'})));
Wed May 09 2012 00:00:00 GMT+0300 (EEST)
I hope that helps someone.
Moment.js will handle this:
var momentDate = moment('23.11.2009 12:34:56', 'DD.MM.YYYY HH:mm:ss');
var date = momentDate.;
You can use the moment.js library for this. I am using only to get time-specific output but you can select what kind of format you want to select.
Reference:
1. moment library: https://momentjs.com/
2. time and date specific functions: https://timestamp.online/article/how-to-convert-timestamp-to-datetime-in-javascript
convertDate(date) {
var momentDate = moment(date).format('hh : mm A');
return momentDate;
}
and you can call this method like:
this.convertDate('2020-05-01T10:31:18.837Z');
I hope it helps. Enjoy coding.
To fully satisfy the Date.parse convert string to format dd-mm-YYYY as specified in RFC822,
if you use yyyy-mm-dd parse may do a mistakes.
//Here pdate is the string date time
var date1=GetDate(pdate);
function GetDate(a){
var dateString = a.substr(6);
var currentTime = new Date(parseInt(dateString ));
var month =("0"+ (currentTime.getMonth() + 1)).slice(-2);
var day =("0"+ currentTime.getDate()).slice(-2);
var year = currentTime.getFullYear();
var date = day + "/" + month + "/" + year;
return date;
}

Categories

Resources