comparing only month in date string Javascript - javascript

i have two dates Date1 and Date2 in format ("Wed Apr 21 2020") .I want to compare only months from two date strings.Forex ample Date1="Fri Sep 13 2020" and Date2="Sun Feb 21 2020" and now i want to compare September from DATE1 with February from DATE2 in such a way .
if(September>February){
var X=greater
}else{
var X=smaller
}
how can i achieve this in JAVASCRIPT

The easiest way is to extract the month from the string and get its index by using an array. See an example below:
const Date1 = 'Fri Sep 13 2020';
const Date2 = 'Sun Feb 21 2020';
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const getMonthIndex = date => months.indexOf(date.split(' ')[1]);
if (getMonthIndex(Date1) > getMonthIndex(Date2)) {
// var X=greater
console.log('greater');
} else {
// var X=smaller
console.log('smaller');
}

Related

Convert date to Month Year using Javascript

I have a Date() object in Javascript. How can I convert it to show "Month Year" (example: Oct 2021).
I tried the following code and it works too. However, I have to convert a lot of dates to this format and it has performance issues.
const date = new Date();
const month = date.toLocaleString('default', { month: 'short' });
const year = date.toLocaleString('default', { year: 'numeric' });
Note: I don't want to use JQuery or other libraries.
If performance is such a concern, why not just reduce some complexity and use getMonth()/getYear() and manually map the abbreviated month names?
const date = new Date();
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
console.log(months[date.getMonth()] + " " + date.getFullYear())
It's provably faster than the other methods posited here, even with the requirement to declare months.

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));

Format Date to human readable within function

I have a function that I am trying to get to format the date and time or just the date at the moment.
function(){
var d = new Date();
var n = d.getTime();
return 'VZW Dfill - ' + n;}
What I have tried
function(){
var d = new Date();
return 'VZW Dfill - ' + d;}
This returns
VZW Dfill - Thu Jan 30 2020 103924 GMT-0500 (Eastern Standard Time)
I would like the format to be 2020JAN30
I have also tried the following but this does not work
function(){
var d = new Date('YYYYMDD');
return 'VZW Dfill - ' + d;}
The above breaks the function.
Any help is appreciated.
This is actually surprisingly complex using pure JavaScript. Here's one (of many) solutions:
var now = new Date();
var months = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'];
var formattedDate = now.getFullYear() + months[now.getMonth()] + now.getDate();
alert(formattedDate);
Using your code from above, write the following function:
function(){
var d = new Date();
var months = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'];
d = d.getFullYear() + months[d.getMonth()] + d.getDate();
return 'VZW Dfill - ' + d;}
There is a pretty extensive thread about formatting JavaScript dates here. Most of them involve (common) third party packages.
You can use also locale
console.log(today.toLocaleDateString("zh-TW")); // 2020/1/30

Time conversions in javascript

How to convert this type of a time
Thu Jul 17 2014 09:52:30 GMT+0300 (Turkey Daylight Time)
to
17 Jul 2014 09:52
and this
17 Jul 2014
Try this code:
var formatDate = function (txt) {
var dt = new Date(txt);
var fmt = dt.getDate();
var sp = " ";
fmt += sp;
fmt += ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][dt.getMonth()];
fmt += sp;
fmt += dt.getFullYear();
return isNaN(dt) ? txt : fmt;
};
var formatDateTime = function (txt) {
var dt = new Date(txt);
var fmt = formatDate(txt);
if (isNaN(dt)) {
fmt = txt;
} else {
fmt += " ";
fmt += dt.getHours();
fmt += ":";
fmt += dt.getMinutes();
}
return fmt;
};
console.log(formatDateTime("Thu Jul 17 2014 09:52:30 GMT+0300 (Turkey Daylight Time)"));
console.log(formatDate("Thu Jul 17 2014 09:52:30 GMT+0300 (Turkey Daylight Time)"));
Although JavaScript provides a bunch of methods for getting and setting parts of a date object, it lacks a simple way to format dates and times according to a user-specified mask.
Whateverdate.format("dd mmm yyyy hh:MM")
Whateverdate.format("dd mmm yyyy")
You can read more here

Convert Javascript String to specific format

I have this String :
var str = "Thu, 10 Apr 2014 09:19:08 +0000";
I would like to get this format : "10 Apr 2014"
How can i do that?
var str = "Thu, 10 Apr 2014 09:19:08 +0000";
var d = new Date(str);
var month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
var b= d.getDate()+' '+month[d.getMonth()]+' '+d.getFullYear();
alert(b);
Check the result in
JSFiddle
You can split the string on spaces and take the second to the fourth items and join:
var d = str.split(' ').slice(1, 4).join(' ');
Demo: http://jsfiddle.net/Guffa/7FuD6/
you can use the substring() method like this,
var str = "Thu, 10 Apr 2014 09:19:08 +0000";
var res = str.substring(5,15);
var str = "Thu, 10 Apr 2014 09:19:08 +0000",
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
d = new Date(str);
d.getDate() + " " + months[d.getMonth()] + " " + d.getFullYear(); //"10 Apr 2014"
The date string you have can be passed into the Date constructor to get a date object, d. The date object has various methods to that gives day, year, month, time etc. Since months are returned as an integer and we need the name, we use an array called months.

Categories

Resources