Jquery- date conversion issue - javascript

My current time zone is getting added when converting date using "new Date()".
var date = "2019-06-03T23:32:59.2354387Z";
var date1 = new Date(date);
console.log(date1);
Expected result: 03-Jun-19 23:32:00
Actual result: 04-Jun-19 02:32:00
please find the fiddle here
https://jsfiddle.net/as6htw9p/

More specific to your scenario with keeping the format, this should work. It's just a shame that the integers provided are formatted like '1' instead of '01' so I have had to add a ‘0’ to the start of the variables.
This should output the exact result you want.
var date = new Date();
var monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug',
'Sep', 'Oct', 'Nov', 'Dec']
var day = '0' + (date.getDay() + 2); // 003
day = day.slice(-2) + '-'; // 03-
var month = date.getMonth(); // 5
month = monthNames[month]; // Jun
month = month + '-'; // Jun-
var year = date.getFullYear() + ''; // 2019
year = year.slice(-2) + ' '; // 19
var hour = '0' + date.getHours(); // 018
hour = hour.slice(-2) + ':'; // 18:
var minutes = '0' + date.getMinutes(); // 025
minutes = minutes.slice(-2) + ':'; // 25:
var seconds = '0' + date.getSeconds(); // 06
seconds = seconds.slice(-2); // 06
var now = day + month + year + hour + minutes + seconds;

Date output in JavaScript is by default in local time. You should use UTC get/set if you need GMT format.
Try this:
utc_date = date1.toUTCString();
console.log(utc_date);

Related

How to convert particilar format date to yyyy-mm-dd format in javascript

Tried to convert date format but not working.
my input is 23th Oct 2054 output shoud be like 2054-10-23. How to do it in javascript?
my code is not working.
function formatDate(date) {
var m = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
return [year, month, day].join('-');
}
var dates = ["23th Oct 2054", "29th Jul 2014", "12th May 2054", "20th Jun 2050", "23th Dec 2059"];
var results=formatDate(dates);
console.log(results.join('\n'),+'\n');
output should be
2054-10-23
2014-07-29
2054-05-12
2050-06-20
2059-12-23
Here is a dirty regex solution that does not use the Date object:
function formatDate(date) {
var newDates = date.map((item) => {
var m = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
var day = item.match(/\d+/)[0];
day = day < 10 ? "0" + day : day;
var month = m.indexOf(item.match(/\s([A-Za-z]{3})\s/)[1]) + 1;
month = month < 10 ? "0" + month : month;
var year = item.match(/\d{4}$/)[0];
return `${year}-${month}-${day}`;
});
return newDates;
}
var dates = ["23th Oct 2054", "29th Jul 2014", "12th May 2054", "20th Jun 2050", "23th Dec 2059"];
console.log(formatDate(dates));
In your example, you are passing an array into your function when it is expecting a string. You are also getting an invalid date object because Date does not accept your format.
Date will accept an ISO Date (2054-10-23), a short date (10/23/2054), or a long date (Oct 23 2054). Your format is very close to the "long date" format.
By removing the "-th", "-nd" or "-st" from your dates, it becomes an accepted long date format which you can pass when initializing a new Date:
new Date(date.replace(/th|nd|st/, ""));
Your function works as intended now (assuming you are passing in a string instead of an array).
Cleaned up example:
function formatDate(date) {
const dateObj = new Date(date.replace(/th|nd|st/, ""));
let year = dateObj.getFullYear();
let month = dateObj.getMonth() + 1;
let day = dateObj.getDate();
if (month.length < 2) month = "0" + month;
if (day.length < 2) day = "0" + day;
return [year, month, day].join("-");
}
var dates = ["23th Oct 2054", "29th Jul 2014", "12th May 2054", "20th Jun 2050", "23th Dec 2059"];
dates.forEach(date => console.log(formatDate(date)));
I recommend using date-fns or moment when working with dates. Formatting them becomes much easier!
Uh, I just did it manually
function formatDate(date) {
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
[d,m,y]=date.split(' ');
d=d.split('').filter(a=>!isNaN(a)).join('');
return [y,m,d].join('-');
}
var dates = ["23th Oct 2054", "29th Jul 2014", "12th May 2054", "20th Jun 2050", "23th Dec 2059"];
dates.forEach(a=>console.log(formatDate(a)))
In one word, MOMENT! :)
If you can get rid of the -th, -rd on the day number, you can use this great library (which is extremely flexible and useful).
-> https://momentjs.com/
var dates = ["23 Oct 2054", "29 Jul 2014", "12 May 2054", "20 Jun 2050", "23 Dec 2059"];
console.log(dates.map(date => moment(date, 'DD MMM YYYY').format('YYYY-MM-DD')));
<script src="https://momentjs.com/downloads/moment.js"></script>
<div id='html'></div>
The first problem is that you're passing an array to a function that doesn't accept an array. Secondly you're passing an invalid date format to Date().
This doesn't use Date(). It just assumes the last 4 digits are the year, the first 1-2 digits are the day, and that the month is in the middle. Case insensitive and whole month is allowed in date format.
function formatDate(date) {
var m = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];
var month = String(m.indexOf(date.split(/[\s-]/)[1].slice(0, 3).toLowerCase())+1),
day = date.split(/[^0-9]/)[0],
year = date.slice(-4);
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
return [year, month, day].join('-');
}
;
for (var dates = ["23th Oct 2054", "29th Jul 2014", "12th May 2054", "20th Jun 2050", "23th dec 2059"], i=0; i<dates.length; i++) {
console.log(formatDate(dates[i]));
}
You can use the below code for this.
var dates = ["23th Oct 2054", "29th Jul 2014", "12th May 2054", "20th Jun 2050", "23th Dec 2059"];
console.log(formatDate(dates));
function formatDate(date) {
var mainArr = [];
if(!Array.isArray(date)) {
date = [date];
}
for(i=0;i<date.length;i++) {
var dateVal = date[i];
var dateValArr = dateVal.split(' ');
var filterDateArr = [];
for(j=0;j<dateValArr.length;j++) {
var val = dateValArr[j]
if(j==0) {
var val = dateValArr[j].replace(/\D/g, "");
}
filterDateArr.push(val);
}
var filterDate = filterDateArr.join(' ');
var d = new Date(filterDate),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) {
month = '0' + month;
}
if (day.length < 2) {
day = '0' + day;
}
mainArr.push([year, month, day].join('-'));
}
return mainArr;
}
You are passing array to function and operating on single item, also invalid string is passed to Date object. Check out below code
function formatDate(dates) {
var result=[]
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
for (i = 0; i < dates.length; i++) {
[d,m,y]=dates[i].split(' ');
day=d.slice(0,d.length-2)
month = (months.indexOf(m)+1).toString();
year = y;
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
result.push([year, month, day].join('-'));
}
return result;
}
var dates = ["23th Oct 2054", "29th Jul 2014", "12th May 2054", "20th Jun 2050", "23th Dec 2059"];
console.log(formatDate(dates));

Convert String (30-jul-2016) into Date(2016-07-30) using Javascript

I want to convert string in date format.
My String format is 30-Jul-2016 And want to convert into 2016-07-30. Only using javascript.
To be as dynamic as possible I advise to implement first Douglas Crockford's supplant function, and assign it to String Object's prototype (How can I do string interpolation in JavaScript?). Here's how you do it:
String.prototype.supplant = function (o) {
return this.replace(/{([^{}]*)}/g,
function (a, b) {
var r = o[b];
return typeof r === 'string' || typeof r === 'number' ? r : a;
}
);
};
After that, you can implement something like this:
function changeFormat(from, to){
var months = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec'
];
var date = new Date(from);
return to.supplant({
YYYY: date.getFullYear(),
MMM: months[date.getMonth()],
MM: date.getMonth()+1 > 9 ? date.getMonth()+1 : '0'+parseInt(date.getMonth()+1),
DD: date.getDate() > 9 ? date.getDate() : '0' + parseInt(date.getDate())
})
}
And this is how it would work:
changeFormat("30-Jul-2016","{YYYY}-{MM}-{DD}") // 2016-07-30
Example:
String.prototype.supplant = function (o) {
return this.replace(/{([^{}]*)}/g,
function (a, b) {
var r = o[b];
return typeof r === 'string' || typeof r === 'number' ? r : a;
}
);
};
function changeFormat(from, to){
var months = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec'
];
var date = new Date(from);
return to.supplant({
YYYY: date.getFullYear(),
MMM: months[date.getMonth()],
MM: date.getMonth()+1 > 9 ? date.getMonth()+1 : '0'+parseInt(date.getMonth()+1),
DD: date.getDate() > 9 ? date.getDate() : '0' + parseInt(date.getDate())
})
}
console.log(changeFormat("30-Jul-2016","{YYYY}-{MM}-{DD}"));
var d = new Date('30-Jul-2016'.split('-').join(' ')),
dFormated = d.getFullYear() + '-' + ('0' + (d.getMonth() + 1)).slice(-2) + '-' + d.getDate();
console.log(dFormated);
Another way:
function formatDate(string) {
var date = new Date(string),
dd = date.getDate(),
mm = date.getMonth() + 1,
yyyy = date.getFullYear();
dd = dd < 10 ? '0' + dd : dd;
mm = mm < 10 ? '0' + mm : mm;
return yyyy + '-' + mm + '-' + dd;
}
console.log(formatDate('30-Jul-2016')); // 2016-07-30
Without a library, like Moment, the best way would be to keep an array of months to get the numerical values (there's no guarantee every browser will parse that date), and then just split the string and parse it
var months = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec'
];
function pad(x) {return x < 10 ? '0' + x : x}; // zero padding
var str = "30-Jul-2016";
var parts = str.split('-');
var date = new Date(parts[2], months.indexOf(parts[1]), parts[0]);
// now you can output whatever
var new_date = date.getFullYear() + '-' + pad(date.getMonth() + 1) + '-' + pad(date.getDate());
document.body.innerHTML = new_date;
Try this
var date = '30-Jul-2016';
date = date.split('-').join(' ');
var d = new Date(date);
alert(d.getFullYear() + '-'+(d.getMonth()+1) +'-'+ d.getDate());
console.log(d.getFullYear() + '-'+(d.getMonth()+1) +'-'+ d.getDate());
Try this code
var date = '30-Jul-2016';
date = date.split('-').join(' ');
var d = new Date(date);
dd = d.getDate();
mm = d.getMonth() + 1;
yyyy = d.getFullYear();
dd = dd < 10 ? '0' + dd : dd;
mm = mm < 10 ? '0' + mm : mm;
alert(yyyy + '-'+mm +'-'+ dd);

Convert m-yyyy format to string

I have a date format that is like this
"5-2015"
How can I convert it so that it appears as "May 2015" on screen?
You could try MomentJS http://momentjs.com/ which is a Date/Time library for Javascript. I believe the syntax would be moment(yourDate, 'M-YYYY').format('MMM YYYY');
If you want to roll your own:
function format(date) {
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
var month = date.substring(0, date.indexOf('-'));
var year = date.substring(date.indexOf('-') + 1);
return months[parseInt(month) - 1] + ' ' + year;
}
var formatted = format('5-2015');
Assuming all of your dates are in the format of "5-2015" (e.g. 6-2015 or 12-2015), what you can do is use the split function on javascript split the string value into months and years.
For example:
var date = "5-2015";
date.split("-"); //splits the date whenever it sees the dash
var month;
if(date[0] == "5"){ //accesses the first split value (the month value) and check if it's a month.
month = "May";
} //do this with the rest of the months.
var finalString = month + " " + date[1]; //constructs the final string, i.e. May 2015
alert(finalString);
You can go like this:
function parseDate(dateString) {
var d = dateString.split("-"); // ["5", "2015"]
// Month is 0-based, so subtract 1
var D = new Date(d[1], d[0]-1).toString().split(" "); // ["Fri", "May", "01", "2015", "00:00:00", "GMT+0200", "(Central", "Europe", "Daylight", "Time)"]
return D[1] + " " + D[3];
}
(function() {
alert(parseDate("5-2015"));
}());

Format and compare Dates in Javascript [duplicate]

This question already has answers here:
Compare two dates with JavaScript
(44 answers)
Closed 8 years ago.
I am trying to do date comparison in javascript.Through a web service call I am getting a date in the form of ""2014-07-02T09:49:49.299Z" and from database I am getting the dat like "2014-07-11 16:01:34".I need to compare these two dates after doing some kind of formatting.i am not sure how to format these two kind of dates to a common format.
Thanks in advance.....
You have date string like : -
var date = "2014-07-02T09:49:49.299Z"
You can try this:-
var getDateString = function(date, format) {
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
getPaddedComp = function(comp) {
return ((parseInt(comp) < 10) ? ('0' + comp) : comp)
},
formattedDate = format,
o = {
"y+": date.getFullYear(), // year
"M+": months[date.getMonth()], //month
"d+": getPaddedComp(date.getDate()), //day
"h+": getPaddedComp((date.getHours() > 12) ? date.getHours() % 12 : date.getHours()), //hour
"m+": getPaddedComp(date.getMinutes()), //minute
"s+": getPaddedComp(date.getSeconds()), //second
"S+": getPaddedComp(date.getMilliseconds()), //millisecond,
"t+": (date.getHours() >= 12) ? 'PM' : 'AM'
};
for (var k in o) {
if (new RegExp("(" + k + ")").test(format)) {
formattedDate = formattedDate.replace(RegExp.$1, o[k]);
}
}
return formattedDate;
};
Now to format the date, write:-
getDateString(new Date(date), "h:m:s:t")
And to compare two dates try this
var date = "2014-07-02T09:49:49.299Z";
var date1 = "2013-07-02T09:49:49.299Z";
var compareDate = function(date,date1){
if(new Date(date).getTime()>new Date(date1).getTime()){
console.log("greater date");
} else{
console.log("lesser date");
}
}

Reworking a date string from yyyy-mm-dd to dd/mm/yyyy [duplicate]

This question already has answers here:
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 8 years ago.
I need your help,
how can I rework and restring a date string from yyyy-mm-ddd to dd/mm/yyyy?
Example: 2014-06-27, firstly replace the dash with a slash, then shift the order of the digits around to form 27/06/2014
I am not sure as to how to go about doing this?
Thanks
I've made a custom date string format function, you can use that.
var getDateString = function(date, format) {
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
getPaddedComp = function(comp) {
return ((parseInt(comp) < 10) ? ('0' + comp) : comp)
},
formattedDate = format,
o = {
"y+": date.getFullYear(), // year
"M+": months[date.getMonth()], //month
"d+": getPaddedComp(date.getDate()), //day
"h+": getPaddedComp((date.getHours() > 12) ? date.getHours() % 12 : date.getHours()), //hour
"H+": getPaddedComp(date.getHours()), //hour
"m+": getPaddedComp(date.getMinutes()), //minute
"s+": getPaddedComp(date.getSeconds()), //second
"S+": getPaddedComp(date.getMilliseconds()), //millisecond,
"t+": (date.getHours() >= 12) ? 'PM' : 'AM'
};
for (var k in o) {
if (new RegExp("(" + k + ")").test(format)) {
formattedDate = formattedDate.replace(RegExp.$1, o[k]);
}
}
return formattedDate;
};
And now suppose you've :-
var date = "2014-06-27";
So to format this date you write:-
var formattedDate = getDateString(new Date(date), "d/M/y")
if you're using a string, then the string.split would be an easy way to do this.
C# code:
public void testDateTime()
{
string dashedDate = "2014-01-18"; // yyyy-mm-dd
var stringArray = dashedDate.Split('-');
string newDate = stringArray[2] + "/" + stringArray[1] + "/" + stringArray[0];
//convert to dd/mm/yyyy
Assert.AreEqual(newDate, "18/01/2014");
}

Categories

Resources