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

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.

Related

Javascript date conversion and adding days

I have a date in the form of a string like below:
var dateInput= "Sat Dec 7 2019 00:00:00 GMT+0300 (East Africa Time)";
I want to convert this date to dd/mm/yyyy and be able to add and subtract days from this date and still retain the same format.
Here's what I did to convert this string to dd/mm/yyyy date format:
I used this helper function:
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('/');
}
So, then I did :
var date = new Date(convertDate(eddFromCouch));
which gave me the string 7/12/2019;
Then, when I tried to add the 5 days to the date above, I got the following:
date = date.setDate(date.getDate() + 5);
console.log(date); // returns 1563310800000
I believe 1563310800000 a UNIX timestamp which converts to July,16,2019
I was expecting it to return 12/12/2019.
Here is how you can achieve this using Moment.js. This library makes tasks like parsing, manipulating and displaying dates much easier to achieve.
var input = "2019-08-14T08:06:49.288Z";
var date = moment(input);
date.add(5, "days");
console.log(date.format("DD/MM/YYYY"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
Your dateInput is actually the format returned by date.toString, and can be passed directly to the date constructor to get a date object.
function toDDMMYYY(date) {
let parts = [];
let dd = date.getDate();
let mm = date.getMonth() + 1;
let yyyy = date.getFullYear();
if (dd < 10) {
parts.push(`0${dd}`)
} else {
parts.push(`${dd}`)
}
if (mm < 10) {
parts.push(`0${mm}`)
} else {
parts.push(`${mm}`)
}
parts.push(yyyy)
return parts.join('/');
}
const input = "Sat Dec 7 2019 00:00:00 GMT+0300 (East Africa Time)";
let date = new Date(input);
date = new Date(date.setDate(date.getDate() + 5));
console.log(toDDMMYYY(date))

Formatting JavaScript date

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)

How do get time only , date only and full date in javascript

How do get different form of date datetime and full date depending upon the scenarios.
1 In case date is newest less than 24 Hr old then I have to show like 22:31
In case date is of same month for e.g february but older than 24 hr then I have to show like 15 Feb.
In case date is older than a month then I have to show like 15 Feb 17.
Till now I have made two javascript function for the purpose .
function getLocalizeDateTime(dateString,format) {
if(dateString==null || dateString==undefined || dateString==""){
return "";
}
var dateTime = dateString.trim().split(" ");
var dateOnly = dateTime[0];
var timeOnly = dateTime[1];
timeOnlyOfDate = timeOnly;
var temp = dateOnly + "T" + timeOnly+"Z";
var utc_date =new Date(temp);
currentDateStr = dateString;
//var offset = new Date().getTimezoneOffset();
//utc_date.setMinutes(utc_date.getMinutes() - offset);
if(format!=undefined && format!=null)
return date2str(utc_date,format);
return date.toString();
}
function date2str(x, y) {
var z = {
YR: x.getFullYear(),
M: x.getMonth() + 1,
d: x.getDate(),
h: x.getHours(),
m: x.getMinutes(),
s: x.getSeconds()
};
// Here return 22:32 if date is less than 24 hr old.
// return 24 feb as currentmonth is feb.
// return 24 feb 17 in case current date is march or greater.
y = y.replace(/(M+|d+|h+|m+|s+)/g, function(v) {
return ((v.length > 1 ? "0" : "") + eval('z.' + v.slice(-1))).slice(-2)
});
return y.replace(/(y+)/g, function(v) {
return x.getFullYear().toString().slice(-v.length)
});
}
But these functions return whole date in format for e.g for date "2017-02-24 07:46:38" and format MM-dd-yyyy hh:mm" it is returning 02-24-2017 13:16. How do acheve above mentioned 3 business check.
If you can be sure of support for toLocaleString options, they can be used to format the date string. Otherwise, use a library, e.g.:
function formatTime(date) {
var now = new Date();
var timeOpt = {hour:'2-digit', hour12:false, minute:'2-digit'};
var monthOpt = {day:'numeric', month:'short'};
var fullOpt = {day:'numeric', month:'short', year:'2-digit'};
if (now - date < 8.64e7) {
return date.toLocaleString(undefined, timeOpt);
}
if (now.getFullYear() == date.getFullYear() &&
now.getMonth() == date.getMonth()) {
return date.toLocaleString(undefined, monthOpt);
}
return date.toLocaleString(undefined, fullOpt);
}
// Tests
var soon = new Date();
soon.setHours(soon.getHours() - 2, 23);
var sameMonth = new Date();
sameMonth.setHours(sameMonth.getHours() - 25);
var agesAgo = new Date(2016,5,6,14,27,50);
[soon, sameMonth, agesAgo].forEach(function(date){
console.log(formatTime(date));
})
The sameMonth test will use the fullOpt on the first of the month or before 01:00 on the second as it will set the date to the previous month, but otherwise it will show the more than a day but same month result.
This is my solution. Basically I just cut up the dates to perform conditional tests on them and then stitched them back together. The advantage is that it uses no libraries to do it.
I did grab the 'subtract one day' code from another answer [Link].
$(document).ready ( function() {
var less_than_24 = getLocalizeDateTime(new Date('Fri Feb 24 2017 10:41:28'));
var same_month = getLocalizeDateTime(new Date('Fri Feb 16 2017 13:41:28'));
var older_than_month = getLocalizeDateTime(new Date('Fri Jan 24 2017 13:41:28'));
console.log('less_than_24: ' + less_than_24);
console.log('same_month: ' + same_month);
console.log('older_than_month: ' + older_than_month);
});
function getLocalizeDateTime(dateString,format) {
var monthNames = ['Jan','Feb','Mar','Apr','May','Jun',
'Jul','Aug','Sep','Oct','Nov','Dec'];
if (dateString==null || dateString==undefined || dateString=="") {
return "";
}
var now = new Date();
var hours_24_ago = now;
hours_24_ago.setDate(hours_24_ago.getDate() - 1);
if (dateString >= hours_24_ago) {
return dateString.getHours() + ':' + dateString.getMinutes();
} else if (dateString.getFullYear() == now.getFullYear()
&& dateString.getMonth() == now.getMonth()) {
return (dateString.getDate() + ' ' + monthNames[dateString.getMonth()]);
} else {
return (dateString.getDate() + ' '
+ monthNames[dateString.getMonth()] + ' '
+ dateString.getFullYear());
}
}

problems converting timestamp to new Date

I have a timestamp of:
1399043514913
Which in reality is Fri, 02 May 2014 15:11:54 GMT but I'm getting Sat, 05 Dec 46303 06:35:13 GMT
How can i correctly convert the timestamp to the Fri, 02 May date?
I'm trying:
var dateTime = new Date(milliseconds * 1000);
var UTCString = new Date(dateTime).toUTCString();
What i really want to end up with is a Date object that i can use getDate(), getMonth(), etc on so i can put the date in any format i like.
Alternatively I'd like a way of converting 1399043514913 to 02/05/2014 15:11:54
Update:
Problem solved thanks to #JensB,
Here's my millseconds to date format converter as a result:
function formatTimeStamp(milliseconds) {
if (typeof milliseconds === "string")
milliseconds = parseInt(milliseconds.match(/\d+/g)[0]);
var dateTime = new Date(milliseconds);
var dateVar = new Date(dateTime);
var ISOString = new Date(dateVar).toISOString();
var UTCString = new Date(dateVar).toUTCString();
function pad(s) { return (s < 10) ? ("0" + s) : s.toString(); }
var dateTimeParts = {
dd: pad(dateVar.getDate()),
MM: pad(dateVar.getMonth() + 1),
yyyy: dateVar.getFullYear().toString(),
yy: dateVar.getFullYear().toString().substring(2, 4),
HH: pad(dateVar.getHours()),
mm: pad(dateVar.getMinutes()),
ss: pad(dateVar.getSeconds())
};
var execute = function(string) {
for (var key in dateTimeParts)
string = string.replace(key, dateTimeParts[key]);
return string;
};
return {
ISOString: ISOString,
UTCString: UTCString,
date: execute("dd/MM/yyyy"),
time: execute("HH:mm"),
dateTime: execute("dd/MM/yy HH:mm:ss"),
dateTimeParts: dateTimeParts
};
}
just running this code (same as in your question)
var dateTime = new Date(1399043514913);
var UTCString = new Date(dateTime).toUTCString();
alert(UTCString);
Gives me
Fri, 02 May 2014 15:11:54 GMT
http://jsfiddle.net/DqSGJ/
Edit as per comment, this work?
$( document ).ready(function() {
var dateTime = new Date(1399043514913);
var dateVar = new Date(dateTime);
var UTCString = dateVar.toUTCString();
$("#dt").text(UTCString);
$("#dt2").text("Month: " + dateVar.getMonth());
$("#dt3").text("GetDate: " + dateVar.getDate());
});
Fiddler: http://jsfiddle.net/DqSGJ/3/

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