简体   繁体   中英

How to calculate difference between two dates in {dd-mm-yyyy} format in react native

I want to calculate the difference between two dates in react native my date format is in {dd-mm-yyyy} I have converted the timestamp using moment and put in a variable that is in format {dd-mm-yyyy hh:mm: ss} so I did is split the date and time so now I have a date in another variable in this format{dd-mm-yyyy} I have tried several methods it is showing me, NaN. here is the code:

 const responseJson = [[{"start_date": 1618905463, "end_date": 1618955463 }]] var st_date = responseJson[0][0]['start_date']; { var time_st = moment.unix(st_date).format("DD-MM-YYYY h:mm:ss"); setStartDate(time_st) } //alert(startdate); var start = time_st.split(' ')[0]; //alert(start); var end_date = responseJson[0][0]['end_date']; { var time_en = moment.unix(end_date).format("DD-MM-YYYY h:mm:ss"); setEndDate(time_en) } //alert(enddate); var end = time_en.split(' ')[0]; //alert(end); date1=startdate; date2=enddate; var z = moment('date1', 'DD-MM-YYYY');  var w = moment('date2', 'DD-MM-YYYY'); var v = w.diff(z, 'days'); //alert(v); //alert(diff);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

There is no need to go back and forth between moment instances and strings. Once you have used moment.unix to turn a unix time intoa moment instance you can just use it directly to get the number of days (or hours, minutes, seconds as needed) between the two.

 const responseJson = [[{"start_date": 1618905463, "end_date": 1618955463 }]] var st_date = responseJson[0][0]['start_date']; var time_st = moment.unix(st_date) var end_date = responseJson[0][0]['end_date']; var time_en = moment.unix(end_date) console.log(time_st,time_en); var v = time_st.diff(time_en, 'days'); console.log(v)
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM