MomentJS invalid date - reactjs

I'm trying to convert a date string like 'DD-MM-YYYY', to 'YYYY-MM-DD'.
Unfortunately I'm getting a invalid date.
var startDate = $('.startDate').val();
var endDate = $('.endDate').val();
var newstartDate = moment(startDate).format( "YYYY-MM-DD");
endDate = moment(endDate, "YYYY-MM-DD");
console.log('startDate:',startDate)
console.log('newstartDate:',newstartDate)
console.log('endDate:',endDate)
How could I get the output as: 2018-09-14 . / 2018-08-14 ?

var startDate = "22-12-2009";
var endDate = "01-02-2009";
var newstartDate = moment(startDate,'DD-MM-YYYY').format( "YYYY-MM-DD");
endDate = moment(endDate, 'DD-MM-YYYY');
console.log('startDate:',startDate)
console.log('newstartDate:',newstartDate)
console.log('endDate:',endDate)
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Specify the input date format when parsing with moment moment(startDate,'DD-MM-YYYY').format( "YYYY-MM-DD");

Related

How to convert string to date in react native with moment.js?

I have this date in string, now i want to convert this with UTC using moment.js.
Wednesday, 22 September 2021, 7:00:00 am
Expected result:
Formate: DD-MMM-YYYY hh:mm a
Date: 22-Sep-2021 12:30 PM
I tried this way but not working
let dateStr = 'Wednesday, 22 September 2021, 7:00:00 am'
utcDate = moment(moment(dateStr, 'DD-MMM-YYYY hh:mm a'))
.utc()
.format('DD MMM YYYY, hh:mm A');
Also I tried this conversion with dayjs but it works well in iOS but not in Android where I get null.
utcDate = dayjs(new Date(`${dateStr} UTC`)).format(
'DD MMM YYYY, hh:mm A',
);
let me know if anyone have solution for this.
Thanks!
Try this:
let dateStr = 'Wednesday, 22 September 2021, 7:00:00 am'
const utcDate = moment(new Date(dateStr))
.utc()
.format('DD MMM YYYY, hh:mm A');
console.log(utcDate)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
You need to remove the format from moment call.
You can do this but it is a deprecated way
let dateStr = 'Wednesday, 22 September 2021, 7:00:00 am'
// You can do this but it is deprecated way
const date = moment(dateStr)
.utc()
.format('DD MMM YYYY, hh:mm A');
console.log(date)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
The better solution.
let dateStr = 'Wednesday, 22 September 2021, 7:00:00 am'
const date = moment(new Date(dateStr))
.utc()
.format('DD MMM YYYY, hh:mm A');
console.log(date)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

Add date into array as YYYY-M-DD in reactjs

Now I have a textarea which I enter the date in format 2019-09-15, But I want the date to be printed as 2019-9-15, here is my approach
getDifferenceInDays(startDate, endDate) {
let dateArray = [];
let currentDate = new Date(startDate);
let day = currentDate.getDate() + 1;
let month = currentDate.getMonth() + 1;
let year = currentDate.getFullYear();
currentDate = [year, month, day].join("-");
let endOfDate = new Date(endDate);
let endDay = endOfDate.getDate() + 1;
let endMonth = endOfDate.getMonth() + 1;
let endYear = endOfDate.getFullYear();
endOfDate = [endYear, endMonth, endDay].join("-");
let todayDate = new Date(currentDate);
while (todayDate <= new Date(endOfDate)) {
dateArray.push(currentDate);
todayDate = todayDate.addDays(1);
# currentDate = currentDate.setDate(currentDate.getDate() + 1);
}
return dateArray;
Now I am getting the currentDate as 2019-9-15, but if the startDate is 2019-09-15 and endDate is 2019-09-17 then the currentDate has to be updated like
2019-9-15
2019-9-16
2019-9-17
The line # when I debugged, it says currentDate.setDate as undefined, any solutions to this ? if it helps the entire line throws error
In short I want the date to be displayed as 2019-9-15 and it should increase as per the endate
There are some mistakes in your code.Fyi, you can compare dates using getTime() method of Date object. Here is a full demo how you can generate date and show date from startDate to endDate in a format you mentioned (YYYY-M-DD).The input here is static, just for demo purpose. Obviously, you could make it dynamic on your own.
function getDifferenceInDays(startDate, endDate) {
let dateArray = [];
let currentDate = new Date(startDate);
let day = currentDate.getDate();
let month = currentDate.getMonth()+1;
let year = currentDate.getFullYear();
currentDate = [year, month, day].join("-");
let endOfDate = new Date(endDate);
let endDay = endOfDate.getDate();
let endMonth = endOfDate.getMonth()+1;
let endYear = endOfDate.getFullYear();
endOfDate = [endYear, endMonth, endDay].join("-");
let todayDate = new Date(currentDate);
while (new Date(todayDate).getTime() <= new Date(endOfDate).getTime()) {
let formatTodayDate = new Date(todayDate).getFullYear() +'-'+ (new Date(todayDate).getMonth() + 1) +'-'+ new Date(todayDate).getDate()
dateArray.push(formatTodayDate);
todayDate = new Date(todayDate).setDate(new Date(todayDate).getDate()+1);
}
let demo = document.getElementById("demo")
demo.innerHTML = dateArray
//return dateArray;
}
<button type="button" onclick="getDifferenceInDays('2019-05-15', '2019-05-20')">Show Date</button>
<div id="demo"></div>
currentDate = [year, month, day].join("-");
Strings don't have a setDate method.
Logging the data you're operating on (or inspecting it at a breakpoint) would have shown you the problem immediately, and it would have been faster than asking on SO.

Convert datetime format in string to date javascript?

Let say I have an object product
I can use product.createdDate to get 2018-04-16 15:12:46.179427 or any other date with the same format.
how do I convert to date in javascript so I and show it as 16 April 2018?
I'm using angularjs.
I tried {{product.createdDate | date : 'dd MM, yyyy'}}but it show 2018-04-16 15:12:46.179427
There is no straightforward way to do it. You can find your answer in a similar question here :
Get current date in DD-Mon-YYY format in JavaScript/Jquery
You can try the following:
var date = new Date("2018-04-16 15:12:46.179427".replace(/-/g,"/"));
var d = moment(date).format('D MMMM YYYY')
console.log(d);
<script src="https://rawgit.com/moment/moment/2.2.1/min/moment.min.js"></script>
You can use date pipe to filter it out
html
<p>
{{date | date:'dd MMMM yyyy'}}
</p>
In your controller
$scope.date = new Date("2018-04-16 15:12:46.179427");
To get directly in controller inject $filter
var date = $filter('date')(new Date("2018-04-16 15:12:46.179427"), 'dd MMMM yyyy');
console.log(date); // 16 April 2018
Please refer the demo link
To convert this date using javascript you have to define the months like bellow.
const months = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
const date = new Date('2018-04-16 15:12:46.179427');
const formatedDate = date.getDate() + ' ' + months[date.getMonth()] +' '+ date.getFullYear();
But if you only want to show it in the UI, use a pipe to convert it.

Change date format in angularjs

I am getting date format like this /Date(1497683045200)/. I want to convert it as dd/MM/yyyy. I tried this
<td>{{data.From | date:'MM/dd/yyyy' }}</td>
But format is not changed.Any suggestion?
create a custom filter like this
.filter('jsonDate',function(){
return function(date){
return new Date(date.match(/\d+/)[0] * 1);
}
})
call it like this
<td>{{data.From | jsonDate | date:'MM/dd/yyyy'}}</td>
try this
formatDate(date) {
let 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 [ month, day, year].join('/');
}
Call that custom method on HTML
<td>{{formatDate(data.From)}}</td>

Find difference between 2 dates with AngularJS

I get 2 dates from MySQL something like this:
Start: 2015-11-01 22:56:59 End: 2015-11-03 00:00:00
Also I get dates from object array; here is what one object looks like:
Array[5]
0: Object
$$hashKey: "object:9"
created_at: "2015-10-23 03:36:11"
expiration_date: "2015-11-03 00:00:00"
id: 1
name: "TEST PROJECT"
I need to find how many days left with AngularJS...
Its simple. Use the function as:
$scope.calcDiff = function(firstDate, secondDate){
var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
}
Consider using moment.js for all your javascript date and time manipulations.
With the moment library it is as easy as:
moment(date1).diff(moment(date2), 'days')
You just need to write a js function, that do all calculation instead of you.
<label>{{diffDate(date1, date2) }} </label>
$scope.diffDate = function(date1, date2){
var dateOut1 = new Date(date1); // it will work if date1 is in ISO format
var dateOut2 = new Date(date2);
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
alert(diffDays);
return dateOut;
};
If your data is not in ISO format, you have to set it explicitly.
var dateString = "2015-01-16 22:15:00";
var date = Date.parse(dateString, "yyyy-MM-dd HH:mm:ss");
You can use amDifference filter. Don't forget to inject $filter
let dif = $filter('amDifference')(date1, date2, 'days');

Resources