Formatting JavaScript date - javascript

I have a string representing a date in the following format :
Jun 29, 2019 12:00:00 AM
I would like to format this date such as follows:
2019-06-29
Is there any way of doing this without using any external libraries?
I tried the following and it works fine in Chrome but not in Edge:
var stringDate = 'Jun 29, 2019 12:00:00 AM';
var date = new Date(stringDate).toISOString().slice(0,10);

Using an external lib like https://momentjs.com/ is of course the easiest option.
But if the dates are always in the format you say, maybe a little bit of regex and javascript might be all you need.
eg.
var resplitdate = /^(\w{3}) (\w{1,2}), (\w{4})/;
var months = 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(",");
function pz(s, size) {
var r = s.toString();
while (r.length < size) r = '0' + r;
return r;
}
function convertDate(d) {
var splits = resplitdate.exec(d);
return splits[3] + '-' +
pz(months.indexOf(splits[1]) + 1, 2) + "-" +
pz(splits[2], 2);
}
var stringDate = 'Jun 29, 2019 12:00:00 AM';
console.log(stringDate, " = ", convertDate(stringDate));

You can use getFullYear(), getDay() and getDate() to get the values. You can then use padStart() to pad the beginning of each item with zeros.
var date = new Date('Jun 29, 2019 12:00:00 AM');
console.log(`${date.getFullYear()}-${String(date.getDay()).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`)

A simple way to format the date using javascript(only) could be as follows -
var stringDate = 'Jun 29, 2019 12:00:00 AM';
function appendLeadingZeroes(n){
if(n <= 9){
return "0" + n;
}
return n
}
let current_datetime = new Date(stringDate);
let formatted_date = current_datetime.getFullYear() + "-" + appendLeadingZeroes(current_datetime.getMonth() + 1) + "-" + appendLeadingZeroes(current_datetime.getDate())
console.log(formatted_date)

Related

Converting any kind of date format to MM\DD\YYYY

I am converting this 2 sets of date to the format MM\DD\YYYY
1.Thu Aug 31 15:00:00 GMT+08:00 2017
2017-08-09
When I'm converting the 1st one I use this code.
var STD_Date = STD_data[i][4]; //<----This is where the date comes.
var date = convertDate(STD_Date);
var datearray = date.split("/");
var New_STDDate = datearray[1] + '/' + datearray[0] + '/' + datearray[2];
This is the function convertDate()
function convertDate(inputFormat) {
function pad(s) { return (s < 10) ? '0' + s : s; }
var d = new Date(inputFormat);
return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('/');
}
This is how I format the second one.
This is the function
var toMmDdYy = function(input) {
var ptrn = /(\d{4})\-(\d{2})\-(\d{2})/;
if(!input || !input.match(ptrn)) {
return null;
}
return input.replace(ptrn, '$2/$3/$1');
};
This is how I use it.
var startdate = form.startdate //<--- comes from HTML Picker (Format "YYYY-MM-DD")
toMmDdYy(startdate)
My question is this how can I have a function that will format the date whether it is the 1st or the 2nd one?
Convert_TimeStamp_Date(){
//This is where to code will go to convert
//to MM\DD\YYYY
}
//Then call it
var startdate = "2017-08-08"
var timestamp = "Thu Aug 31 15:00:00 GMT+08:00 2017"
Convert_TimeStamp_Date(startdate);
Convert_TimeStamp_Date(timestamp);
//both of them the output must be "MM\DD\YYYY"
This is the current code but looking forward for a better one. WORKING
//Time Stamp to MM\DD\YYYY
function convertDate(inputFormat) {
function pad(s) { return (s < 10) ? '0' + s : s; }
var d = new Date(inputFormat);
var chopdate = [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('/');
var datearray = chopdate.split("/");
var newdate = datearray[1] + '/' + datearray[0] + '/' + datearray[2];
return newdate;
}
//YYYY-MM-DD tp MM\DD\YYYY
var toMmDdYy = function(input) {
var ptrn = /(\d{4})\-(\d{2})\-(\d{2})/;
if(!input || !input.match(ptrn)) {
return null;
}
return input.replace(ptrn, '$2/$3/$1');
};
//Convert Date based on input to MM\DD\YYYY
function ConverSpedDate(input){
if( input.lenght > 10 ) return toMmDdYy(input);
return convertDate(input);
}
This should work
convertDate = function( input ){
if( input.lenght > 10 ) return convertDate( input );
return toMmDdYy( input );
}
You can test each pattern and reformat accordingly. Your reformatting functions appear to be cumbersome and error prone, consider the following:
var startdate = "2017-08-23"
var timestamp = "Thu Aug 31 15:00:00 GMT+08:00 2017"
function reformatTimestamp(s) {
if (/\d{4}-\d\d-\d\d/.test(s)) {
return reformatISOtoMDY(s);
} else if (/[a-z]{3} [a-z]{3} \d\d \d\d:\d\d:\d\d \w{3}\+\d\d:\d\d \d{4}/i.test(s)) {
return reformatCustomToMDY(s);
}
}
// Reformat YYYY-MM-DD to MM\DD\YYYY
function reformatISOtoMDY(s) {
var b = s.split(/\D/);
return b[1] + '\' + b[2] + '\' + b[0];
}
function reformatCustomToMDY(s) {
var months = '. jan feb mar apr may jun jul aug sep oct nov dec'.split(' ');
var b = s.split(/ /);
return ('0' + months.indexOf(b[1].toLowerCase())).slice(-2) +
'\' + ('0' + b[2]).slice(-2) + '\' + b[5];
}
console.log(reformatTimestamp(startdate))
console.log(reformatTimestamp(timestamp))
The format MM\DD\YYYY is unusual and likely to confuse.
As you've tagged this as a GAS question, have you looked at Utilities.formatDate()? Documentation here, but in short it takes 3 parameters: a date object, a time-zone string & a format string. The TZ & format are taken from the Java SE SimpleDateFormat class.
In your instance, try this:
var ts = "Thu Aug 31 15:00:00 GMT+08:00 2017";
var d = new Date(ts);
Logger.log(Utilities.formatDate(d, "GMT+08:00", "MM/dd/yyyy")); // logs 08/31/2017
Note that you will have to set the time-zone in the output yourself. You could extract it from the timestamp via a regex, for example. As the JS Date primitive is milliseconds 1970-01-01T00:00:00 UTC, you can set your output TZ to suit your needs.
I also +1 the recommendations to stick to ISO date & time formats: MM/dd/yyyy absent locale information is just asking for trouble.

Format dates in Javascript

I have to log my error with datetime in some file, for that I am using following code:
var dLogDate = new Date();
console.log(dLogDate.toString().substring(4) + ', ' + dLogDate.toGMTString().substring(4));
as per above code output comes as follows which is nice but not formated as I need:
"Oct 10 2014 12:48:59 GMT+0530 (IST), 10 Oct 2014 07:18:59 GMT"
I want result s follows :
"10 Oct 2014 12:48:59 (IST), 10 Oct 2014 07:18:59 (GMT)"
see date part before ",". I need 10 Oct instated of Oct 10
This can be done with some function which is substring first 4 character from string and concat at 3rd position again, But I am still curious to know if there are any other simple way to do this? I don't want to use any third party library/script.
Thanks.
You could try adding to the prototype an extension method toISTString
function pad(n) {
return (n < 10) ? '0' + n : n;
}
Date.prototype.toISTString = function(locale) {
var year = this.getFullYear().toString();
var month = this.toLocaleString(locale, { month: "short" }) // ECMAScript Internationalization API, which is very new only available in Blink browsers (Chrome and Opera), IE11, and Firefox 29+.
var day = this.getDate().toString();
var hrs = this.getHours().toString();
var mins = this.getMinutes().toString();
var secs = this.getSeconds().toString();
return day + " " + month + " " + year + " " + pad(hrs) + ":" + pad(mins) + ":" + secs + " (IST)";
};
dLogDate = new Date();
console.log(dLogDate.toISTString("en-us") + ', ' + dLogDate.toGMTString().substring(4));
JSFiddle
You can use date functions to format date
http://www.w3schools.com/jsref/jsref_obj_date.asp
var monthIndex = date.getMonth();
var dayIndex = date.getDay();
var monthArray = ['January',....];
var dayArray = ['Sunday',...]
console.log(monthArray[monthIndex] + "-" + dayArray[dayIndex]);

Add days to date using Javascript

I am trying to add days to a given date using Javascript. I have the following code:
function onChange(e) {
var datepicker = $("#DatePicker").val();
alert(datepicker);
var joindate = new Date(datepicker);
alert(joindate);
var numberOfDaysToAdd = 1;
joindate.setDate(joindate + numberOfDaysToAdd);
var dd = joindate.getDate();
var mm = joindate.getMonth() + 1;
var y = joindate.getFullYear();
var joinFormattedDate = dd + '/' + mm + '/' + y;
$('.new').val(joinFormattedDate);
}
On first alert I get the date 24/06/2011 but on second alert I get Thu Dec 06 2012 00:00:00 GMT+0500 (Pakistan Standard Time) which is wrong I want it to remain 24/06/2011 so that I can add days to it. In my code I want my final output to be 25/06/2011.
Fiddle is # http://jsfiddle.net/tassadaque/rEe4v/
Date('string') will attempt to parse the string as m/d/yyyy. The string 24/06/2011 thus becomes Dec 6, 2012. Reason: 24 is treated as a month... 1 => January 2011, 13 => January 2012 hence 24 => December 2012. I hope you understand what I mean. So:
var dmy = "24/06/2011".split("/"); // "24/06/2011" should be pulled from $("#DatePicker").val() instead
var joindate = new Date(
parseInt(dmy[2], 10),
parseInt(dmy[1], 10) - 1,
parseInt(dmy[0], 10)
);
alert(joindate); // Fri Jun 24 2011 00:00:00 GMT+0500 (West Asia Standard Time)
joindate.setDate(joindate.getDate() + 1); // substitute 1 with actual number of days to add
alert(joindate); // Sat Jun 25 2011 00:00:00 GMT+0500 (West Asia Standard Time)
alert(
("0" + joindate.getDate()).slice(-2) + "/" +
("0" + (joindate.getMonth() + 1)).slice(-2) + "/" +
joindate.getFullYear()
);
Demo here
I would like to encourage you to use DateJS library. It is really awesome!
function onChange(e) {
var date = Date.parse($("#DatePicker").val()); //You might want to tweak this to as per your needs.
var new_date = date.add(n).days();
$('.new').val(new_date.toString('M/d/yyyy'); //You might want to tweak this as per your needs as well.
}
Assuming numberOfDaysToAdd is a number:
joindate.setDate(joindate.getDate() + numberOfDaysToAdd);
The first alert is the value of the field. the second is the generated date from a non-US formatted date.
Here is a working example (seems that this kind of markup is necessary to get noticed)
If you want to keep your code, then you need to change
var joindate = new Date(datepicker);
to
var parms = datepicker.split("/");
then use
var joindate = new Date(parms[1]+"/"+parms[0]+"/"+parms[2]);
OR the identically working
var joindate = new Date(parms[2],parms[1]-1,parms[0]);
As pointed out in a few other answers too, use the .getDate()
joindate.setDate(joindate.getDate() + numberOfDaysToAdd);
Lastly you want to add a 0 if the month is < 10
if (mm<10) mm="0"+mm;
If you are using the datepicker from jQuery UI, then you can do
$('.new').val($("#DatePicker").datepicker( "setDate" , +1 ).val());
instead of your function
http://jqueryui.com/demos/datepicker/#method-setDate
Sets the current date for the
datepicker. The new date may be a Date
object or a string in the current date
format (e.g. '01/26/2009'), a number
of days from today (e.g. +7) or a
string of values and periods ('y' for
years, 'm' for months, 'w' for weeks,
'd' for days, e.g. '+1m +7d'), or null
to clear the selected date.
Try
function onChange(e) {
var datepicker = $("#DatePicker").val();
alert(datepicker);
var parts = datepicker.split(/[^\d]/);
var joindate = new Date();
joindate.setFullYear(parts[2], parts[1]-1, parts[0]);
alert(joindate);
var numberOfDaysToAdd = 1;
joindate.setDate(joindate + numberOfDaysToAdd);
var dd = joindate.getDate();
var mm = joindate.getMonth() + 1;
var y = joindate.getFullYear();
var joinFormattedDate = dd + '/' + mm + '/' + y;
$('.new').val(joinFormattedDate);
}
I suppose the problem is JavaScript expects format MM/DD/YYYY not DD/MM/YYYY when passed into Date constructor.
To answer your real problem, I think your issue is that you're trying to parse the text-value of the DatePicker, when that's not in the right format for your locale.
Instead of .val(), use:
var joindate = $('#DatePicker').datepicker("getDate");
to get the underyling Date() object representing the selected date directly from jQuery.
This guarantees that the date object is correct regardless of the date format specified in the DatePicker or the current locale.
Then use:
joindate.setDate(joindate.getDate() + numberOfDaysToAdd);
to move it on.
Is it a typo round joindate.setDate(joindate + numberOfDaysToAdd)?
I tried this code, it seems ok to me
var joindate = new Date(2010, 5, 24);
alert(joindate);
var numberOfDaysToAdd = 1;
joindate.setDate(joindate.getDate() + numberOfDaysToAdd);
var dd = joindate.getDate();
var mm = joindate.getMonth() + 1;
var y = joindate.getFullYear();
var joinFormattedDate = dd + '/' + mm + '/' + y;
alert(joinFormattedDate);
Date.prototype.addDays = function(days) {
this.setDate(this.getDate() + days);
return this;
};
and in your javascript code you could call
var currentDate = new Date();
// to add 8 days to current date
currentDate.addDays(8);
function onChange(e) {
var datepicker = $("#DatePicker").val().split("/");
var joindate = new Date();
var numberOfDaysToAdd = 1;
joindate.setFullYear(parseInt(datepicker[2]), parseInt(datepicker[1])-1, parseInt(datepicker[0])+numberOfDaysToAdd);
$('.new').val(joindate);
}
http://jsfiddle.net/roberkules/k4GM5/
try this.
Date.prototype.addDay = function(numberOfDaysToAdd){
this.setTime(this.getTime() + (numberOfDaysToAdd * 86400000));
};
function onChange(e) {
var date = new Date(Date.parse($("#DatePicker").val()));
date.addDay(1);
var dd = date.getDate();
var mm = date.getMonth() + 1;
var y = date.getFullYear();
var joinFormattedDate = dd + '/' + mm + '/' + y;
$('.new').val(joinFormattedDate);
}

date format javascript

The script below returns dates in this format:
Fri Apr 21 2011 12:18:25 GMT+0200
Fri Apr 22 2011 12:18:25 GMT+0200
Fri Apr 29 2011 12:18:25 GMT+0200
My question is: how to get dates in this format:
dd/mm/year like so: 21/04/2001
function addDays(dateObj, numDays) {
dateObj.setDate(dateObj.getDate() + numDays);
return dateObj;
}
var now = new Date();
var tomorrow = addDays(new Date(), 1);
var nextWeek = addDays(new Date(), 8);
{
jQuery("input[id*='now']").val(now);
jQuery("input[id*='tomorrow']").val(tomorrow);
jQuery("input[id*='nextweek']").val(nextWeek);
}
var date = new Date();
var d = date.getDate();
var day = (d < 10) ? '0' + d : d;
var m = date.getMonth() + 1;
var month = (m < 10) ? '0' + m : m;
var yy = date.getYear();
var year = (yy < 1000) ? yy + 1900 : yy;
alert(day + "/" + month + "/" + year);
Try this.
I suggest you can use Steve Levithan's dateformat script: http://blog.stevenlevithan.com/archives/date-time-format
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
document.write(curr_date + "-" + curr_month + "-" + curr_year);
You just may wrap it or use one of the existing helpers
Check out moment.js! It's a really powerful little library for working with Dates in JavaScript.
var today = moment(new Date());
today.format("D/M/YYYY"); // "4/11/2012"
today.format("MMMM D, YYYY h:m A"); // outputs "April 11, 2012 2:42 PM"
// in one line...
moment().format("D/M/YYYY"); // "4/11/2012"
moment().format("MMMM D, YYYY h:m A"); // outputs "April 11, 2012 2:42 PM"
Another example...
var a = moment([2012, 2, 12, 15, 25, 50, 125]);
a.format("dddd, MMMM Do YYYY, h:mm:ss a"); // "Monday, March 12th 2012, 3:25:50 pm"
a.format("ddd, hA"); // "Mon, 3PM"
Also, its worth mentioning to checkout date.js. I think the two libraries complement each other.
The formatting library https://github.com/anywhichway/stringformatter will address this issue and more. It supports most of the momentjs formats plus U, G, I, L, T, to return UTC, GTM, ISO, Local, and Time strings respectively. It also provides a consistent approach that can be used for formatting other things.
Format expressions using this library take the form of embedded Javascript objects, e.g.
format("{Date: {format: 'DD-MMM-YYYY hh:mm:ss:SSS A'}}",new Date('2015-04-12 00:12:23'));
will return
"12-Apr-2015 12:12:23:000 AM"
Using plain old JavaScript, something like this should work:
var formatDateString = function(s) {
var pad = function(x) { return ((x.length<2) ? "0" : "") + x; }
, dt = new Date("" + s), d, m, y;
if (dt.getTime()) {
d = pad(dt.getDate());
m = pad(dt.getMonth()+1);
y = dt.getFullYear();
return [d, m, y].join('/');
}
return null;
};
formatDateString("Fri Apr 21 2011 12:18:25 GMT+0200"); // => "21/04/2011"
If you're already using jquery UI and the date picker
var stringDate = $.datepicker.formatDate( 'dd/mm/yy', new Date() );
In pure Javascript:
function dmy(d) {
function pad2(n) {
return (n < 10) ? '0' + n : n;
}
return pad2(d.getUTCDate()) + '/' +
pad2(d.getUTCMonth() + 1) + '/' +
d.getUTCFullYear();
}

Convert string to datetime

How to convert string like '01-01-1970 00:03:44' to datetime?
Keep it simple with new Date(string). This should do it...
const s = '01-01-1970 00:03:44';
const d = new Date(s);
console.log(d); // ---> Thu Jan 01 1970 00:03:44 GMT-0500 (Eastern Standard Time)
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
EDIT: "Code Different" left a valuable comment that MDN no longer recommends using Date as a constructor like this due to browser differences. While the code above works fine in Chrome (v87.0.x) and Edge (v87.0.x), it gives an "Invalid Date" error in Firefox (v84.0.2).
One way to work around this is to make sure your string is in the more universal format of YYYY-MM-DD (obligatory xkcd), e.g., const s = '1970-01-01 00:03:44';, which seems to work in the three major browsers, but this doesn't exactly answer the original question.
For this format (assuming datepart has the format dd-mm-yyyy) in plain javascript use dateString2Date. It may bite you, because of browser compatibility problems.
tryParseDateFromString is ES6 utility method to parse a date string using a format string parameter (format) to inform the method about the position of date/month/year in the input string. The date is constructed using Date.UTC, circumventing the aforementioned browser compatibility problems.
See also
// fixed format dd-mm-yyyy
function dateString2Date(dateString) {
const dt = dateString.split(/\-|\s/);
return new Date(dt.slice(0, 3).reverse().join('-') + ' ' + dt[3]);
}
// multiple formats (e.g. yyyy/mm/dd (ymd) or mm-dd-yyyy (mdy) etc.)
function tryParseDateFromString(dateStringCandidateValue, format = "ymd") {
const candidate = (dateStringCandidateValue || ``)
.split(/[ :\-\/]/g).map(Number).filter(v => !isNaN(v));
const toDate = () => {
format = [...format].reduce((acc, val, i) => ({ ...acc, [val]: i }), {});
const parts =
[candidate[format.y], candidate[format.m] - 1, candidate[format.d] ]
.concat(candidate.length > 3 ? candidate.slice(3) : []);
const checkDate = d => d.getDate &&
![d.getFullYear(), d.getMonth(), d.getDate()]
.find( (v, i) => v !== parts[i] ) && d || undefined;
return checkDate( new Date(Date.UTC(...parts)) );
};
return candidate.length < 3 ? undefined : toDate();
}
const result = document.querySelector('#result');
result.textContent =
`*Fixed\ndateString2Date('01-01-2016 00:03:44'):\n => ${
dateString2Date('01-01-2016 00:03:44')}`;
result.textContent +=
`\n\n*With formatting dmy
tryParseDateFromString('01-12-2016 00:03:44', 'dmy'):\n => ${
tryParseDateFromString('01-12-2016 00:03:44', "dmy").toUTCString()}`;
result.textContent +=
`\n\n*With formatting mdy
tryParseDateFromString('03/01/1943', 'mdy'):\n => ${
tryParseDateFromString('03/01/1943', "mdy").toUTCString()}`;
result.textContent +=
`\n\n*With invalid format
tryParseDateFromString('12-13-2016 00:03:44', 'dmy'):\n => ${
tryParseDateFromString('12-13-2016 00:03:44', "dmy")}`;
result.textContent +=
`\n\n*With formatting invalid string
tryParseDateFromString('03/01/null', 'mdy'):\n => ${
tryParseDateFromString('03/01/null', "mdy")}`;
result.textContent +=
`\n\n*With formatting no parameters
tryParseDateFromString():\n => ${tryParseDateFromString()}`;
<pre id="result"></pre>
http://www.w3schools.com/jsref/jsref_parse.asp
<script type="text/javascript">
var d = Date.parse("Jul 8, 2005");
document.write(d);<br>
</script>
You could use the moment.js library.
Then simply:
var stringDate = '01-01-1970 00:03:44';
var momentDateObj = moment(stringDate);
Checkout their api also, helps with formatting, adding, subtracting (days, months, years, other moment objects).
I hope this helps.
Rhys
well, thought I should mention a solution I came across through some trying. Discovered whilst fixing a defect of someone comparing dates as strings.
new Date(Date.parse('01-01-1970 01:03:44'))
https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
var unixTimeZero = Date.parse('01 Jan 1970 00:00:00 GMT');
var javaScriptRelease = Date.parse('04 Dec 1995 00:12:00 GMT');
console.log(unixTimeZero);
// expected output: 0
console.log(javaScriptRelease);
// expected output: 818035920000
formatDateTime(sDate,FormatType) {
var lDate = new Date(sDate)
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";
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 hh = lDate.getHours() < 10 ? '0' +
lDate.getHours() : lDate.getHours();
var mi = lDate.getMinutes() < 10 ? '0' +
lDate.getMinutes() : lDate.getMinutes();
var ss = lDate.getSeconds() < 10 ? '0' +
lDate.getSeconds() : lDate.getSeconds();
var d = lDate.getDate();
var dd = d < 10 ? '0' + d : d;
var yyyy = lDate.getFullYear();
var mon = eval(lDate.getMonth()+1);
var mm = (mon<10?'0'+mon:mon);
var monthName=month[lDate.getMonth()];
var weekdayName=weekday[lDate.getDay()];
if(FormatType==1) {
return mm+'/'+dd+'/'+yyyy+' '+hh+':'+mi;
} else if(FormatType==2) {
return weekdayName+', '+monthName+' '+
dd +', ' + yyyy;
} else if(FormatType==3) {
return mm+'/'+dd+'/'+yyyy;
} else if(FormatType==4) {
var dd1 = lDate.getDate();
return dd1+'-'+Left(monthName,3)+'-'+yyyy;
} else if(FormatType==5) {
return mm+'/'+dd+'/'+yyyy+' '+hh+':'+mi+':'+ss;
} else if(FormatType == 6) {
return mon + '/' + d + '/' + yyyy + ' ' +
hh + ':' + mi + ':' + ss;
} else if(FormatType == 7) {
return dd + '-' + monthName.substring(0,3) +
'-' + yyyy + ' ' + hh + ':' + mi + ':' + ss;
}
}
By using Date.parse() you get the unix timestamp.
date = new Date( Date.parse("05/01/2020") )
//Fri May 01 2020 00:00:00 GMT
For this format (supposed datepart has the format dd-mm-yyyy) in plain javascript:
var dt = '01-01-1970 00:03:44'.split(/\-|\s/)
dat = new Date(dt.slice(0,3).reverse().join('/')+' '+dt[3]);
var dt = '01-02-2021 12:22:55'.split(/\-|\s/)
dat = new Date(dt.slice(0,3).reverse().join('/')+' '+dt[3]);
console.log(dat.toLocaleDateString())
enter code here
I found a simple way to convert you string to date.
Sometimes is not correct to convert this way
let date: string = '2022-05-03';
let convertedDate = new Date(date);
This way is not ok due to lack of accuracy, sometimes the day is changed from the original date due to the date's format.
A way I do it and the date is correct is sending the date parameters
let date: string = '2022-05-03';
let d: string = date.split('-');
let convertedDate = new Date(+d[0], +d[1] - 1, +d[2]); //(year:number, month:number, date:number, ...)
console.log(date);
console.log(convertedDate);
This is the Output:
Output
2022-05-03
Tue May 03 2022 00:00:00 GMT-0400 (Atlantic Standard Time)
The date can accept a lot more parameters as hour, minutes, seconds, etc.
After so much reasearch I got my solution using Moment.js:
var date = moment('01-01-1970 00:03:44', "YYYY-MM-DD").utcOffset('+05:30').format('YYYY-MM-DD HH:mm:ss');
var newDate = new Date(moment(date).add({ hours:5, minutes: 30 }).format('YYYY-MM-DD hh:mm:ss'));
console.log(newDate)
//01-01-1970 00:03:44

Categories