Convert IST date format to YYYY-MM-DD in javascript - javascript

I'm getting a date string "Wed Mar 19 00:30:00 IST 1997" and I want to make this as readable YYYY-MM-DD format. Is there any solution to do this with pure javascript?

It seems that your time is not normal javascript date string. if you remove the IST from your string, you can create a date object from it.
dateString = 'Wed Mar 19 00:30:00 IST 1997';
var date = new Date(dateString.replace('IST', ''));
let day = date.getDate();
let month = date.getMonth()+1;
let year = date.getFullYear();
console.log(year+"/"+month+"/"+day)

You can try using the following function
let str = "Wed Mar 19 00:30:00 IST 1997"
function formatDate(date) {
date = date.split(" ");
let monthsList = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
];
let year = date[5];
let month = `0${(monthsList.indexOf(date[1]) + 1)}`.slice(-2);
let day = date[2];
return `${year}-${month}-${day}`;
}
console.log(formatDate(str));

you can try this.
let date = new Date();
let day = date.getDate();
let month = date.getMonth()+1;
let year = date.getFullYear();
console.log(year+"/"+month+"/"+day)

Related

Add days number to string Javascript

I'm looking to add 5 days to the date however because I need a date as dd mmm yy the date has to be a string. The string part works great but as soon as I add anything to the new date value it then doesn't increment the month. Adding any later infers the number as a string.
Thanks
monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
const dateObj = new Date();
const month = monthNames[dateObj.getMonth()];
const day = String(dateObj.getDate()).padStart(2, '0');
const year = dateObj.getFullYear();
const output = + day +'\n'+ month + '\n' + year;
document.write(output)
You can use setDate() to add days to your date. Then you can use toLocaleDateString() to format your date.
const addDays = (days) => {
const date = new Date();
date.setDate(date.getDate() + days);
return date.toLocaleDateString(undefined, {
day: '2-digit',
month: 'short',
year: 'numeric'
});
}
console.log(addDays(5));
.as-console-wrapper { max-height: 100% !important; top: 0; }

How to turn a period of date into an array?

How to turn a period of date in an array? For example, I have a period of date from 1 March 2020 to 29 April 2020, how can I turn it into an array shown below?
period = [{day: "Sun", date: "1", month: "Mar", year: "2020"}, ...,
{day: "Wed",date: "29", month: "Apr", year: "2020"}]
You can create array from date range follow https://stackoverflow.com/a/50398144/4964569
and get day in date follow https://stackoverflow.com/a/4822882/4964569
And use map function to generate your required
var getDaysArray = function(s,e) {for(var a=[],d=new Date(s);d<=e;d.setDate(d.getDate()+1)){ a.push(new Date(d));}return a;};
var dateRange = getDaysArray(new Date('2020-03-10'), new Date('2020-04-29'));
var days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
var result = dateRange.map(function(elem){
var obj = {
day: days[elem.getDay()],
date: elem.getDate(),
month: elem.getMonth(),
year: elem.getFullYear()
}
return obj;
});
console.log(result)
var getDaysArray = function(s,e) {for(var a=[],d=new Date(s);d<=e;d.setDate(d.getDate()+1)){ a.push(new Date(d));}return a;};
var dateRange = getDaysArray(new Date('2020-03-10'), new Date('2020-04-29'));
var days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
var result = dateRange.map(function(elem){
var obj = {
day: days[elem.getDay()],
date: elem.getDate(),
month: elem.getMonth(),
year: elem.getFullYear()
}
return obj;
});
console.log(result)
In traditional way you can do it like this
var startDate = new Date('2020-03-10');
var endDateDate = new Date('2020-03-12');
var arr = [];
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
while(startDate.getTime() !== endDateDate.getTime()) {
startDate.setDate(startDate.getDate() + 1)
arr.push({
day: days[startDate.getDay()],
date: startDate.getDate(),
month: startDate.getMonth(),
year: startDate.getYear()
})
}
console.log(arr);
I'm assuming you have two Dates as your range delimiters. If not, you can create them this way:
var startDate = new Date('1 March 2020')
var endDate = new Date('29 April 2020')
Then, you have to increase the first date by one day until you reach the last date. To increase the first date by one day you can do this:
startDate.setDate(startDate.getDate() + 1)
You can get the day and the month from a Date with date.getDay() and date.getMonth(), but those methods will return numbers. To get the actual names you can do this:
var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
var startDateDay = days[startDate.getDay()]
var startDateMonth = months[startDate.getMonth()]
And then, you iterate:
var period = []
while (startDate <= lastDate) {
period.push({
day: days[startDate.getDay()],
date: startDate.getDate(),
month: months[startDate.getMonth()],
year: startDate.getYear()
})
startDate.setDate(startDate.getDate() + 1)
}
And that's it. Here's a fiddle with a working example:
var startDate = new Date('1 March 2020')
var endDate = new Date('29 April 2020')
var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
var period = []
while (startDate <= endDate) {
period.push({
day: days[startDate.getDay()],
date: startDate.getDate(),
month: months[startDate.getMonth()],
year: startDate.getFullYear()
})
startDate.setDate(startDate.getDate() + 1)
}
console.log(period)
var start = new Date('March 1, 2020');
var period = [];
for(var i=1; i<=60; i++){
if( i == 32 )
start = new Date('April 1, 2020');
if( i <= 31 )
start.setDate(i);
else
start.setDate(i - 31);
var dateString = start.toDateString().split(' ');
period.push({
day: dateString[0],
date: dateString[2],
month: dateString[1],
year: dateString[3]
});
}
console.log( JSON.stringify(period) );

How to get month and year from date in node js

How to get month and year data in Nodejs and query to insert into database?
var months = ["jan", "feb", "mar", "apr", "may", "jun", "july", "aug", "sep", "oct", "nov", "dec"];
var date = new Date();
var month = date.getMonth(); // returns 0 - 11
var year = date.getFullYear();
console.log(months[month]);
console.log(year);
To get the current month and year you can do the following
var date= new Date();
var month = date.getUTCMonth() + 1; //months from 1-12
var year = date.getUTCFullYear();
However i cannot answer on how to save to Database since that depends entirely on the Database and Object Modelling you are using. Can you provide more info on the Database please.
Thanks.

Getting only selected date in bootstrap-date paginator

I am using bootstrap-datepaginator Source.
The below code returns date in this format Sun Aug 14 2016 00:00:00 GMT+0400
Instead of that i want to return it in this format 14/Aug/2016
<script>
$(document).ready(function () {
var options = {
selectedDate: '2016-01-01',
selectedDateFormat: 'YYYY-MM-DD'
}
$('#paginator').datepaginator(options);
$('#paginator').datepaginator();
$('#paginator').on('selectedDateChanged', function (event, date) {
// Your logic goes here
alert(date);
});
});</script>
try this
var months = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Ntove", "Dec" ];
var dati = "Sun Aug 14 2016 00:00:00 GMT+0400";
var date = new Date(dati);
var thedate = date.getDate();
var themonth = date.getMonth();
var theyear = date.getFullYear();
alert(thedate);
alert(themonth);
alert(theyear);
var newdate = thedate +"/"+months[themonth]+"/"+theyear;
alert(newdate);
working example
<html>
<head></head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<body>
</body>
<script type="text/javascript">
var months = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Ntove", "Dec" ];
var dati = "Sun Aug 14 2016 00:00:00 GMT+0400";
var date = new Date(dati);
var thedate = date.getDate();
var themonth = date.getMonth();
var theyear = date.getFullYear();
alert(thedate);
alert(themonth);
alert(theyear);
var newdate = thedate +"/"+months[themonth]+"/"+theyear;
alert(newdate);
</script>
</html>

Specify date format while parsing date in Javascript

I want to parse 7Apr2014.
Most of the custom parsing solutions suggest string manipulation using regex or some other hack.
In Java I could simply do this:
new SimpleDateFormat("ddMMMyyyy").parse("07Apr2014")
Is there no way to do this in Javascript?
Not really, there is a Date.parse function but it is implementation dependent and thus unreliable. Your best bet is to manually parse the date or use a date parser library like datejs.
<script language="Javascript" src="date.js" type="text/javascript" />
console.log(Date.parseExact ('07Apr2014', 'ddMMMyyyy'))
Prints:
Date {Mon Apr 07 2014 00:00:00 GMT+0530 (IST)}
function parseDate(s) {
var months = [ "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec" ];
var monthStarts;
var yearStarts;
for (var i=1; i<s.length; i++) {
var currentCharIsNumb = !isNaN(parseInt(s[i]));
var previousCharWasNumb = !isNaN(parseInt(s[i -1]));
if (!currentCharIsNumb && previousCharWasNumb)
monthStarts = i;
if (currentCharIsNumb && !previousCharWasNumb)
yearStarts = i;
}
var day = parseInt(s.substring(0, monthStarts));
var monthStr = s.substring(monthStarts, yearStarts);
var month = months.indexOf(monthStr.toLowerCase().substring(0, 3));
var year = parseInt(s.substring(yearStarts));
return new Date(year, month, day);
}
Your date format appears not to be part of the formats supported by Date.parse method.
As you already figured out, it appears we need some custom implementation.
Here is a blog that you might find useful/adopt:
http://lpicquet.wordpress.com/2009/11/03/simpledateformat-in-javascript/

Categories

Resources