2019年2月19日 星期二

[ JS 常見問題 ] Time difference in Nodejs?

Source From Here 
Question 
Im trying to figure out a way to get the time difference in seconds between two dates. For example, difference in seconds between: 
Start 2013-5-11 8:37:18 
End 2013-5-11 10:37:18

How-To 
You can leverage moment module: 
  1. var moment = require('moment')  
  2. var startDate = moment('2013-5-11 8:37:18', 'YYYY-M-DD HH:mm:ss')  
  3. var endDate = moment('2013-5-11 10:37:18', 'YYYY-M-DD HH:mm:ss')  
  4. var secondsDiff = endDate.diff(startDate, 'seconds')  
  5. console.log(secondsDiff) // Output 7200  
More usage on moment module: 
> st = moment() 
moment("2019-02-19T19:06:46.633") 
> et = moment() 
moment("2019-02-19T19:06:52.655") 
> et.diff(st, 'seconds') 
6 
> var now = new Date() 
> now 
2019-02-19T11:07:25.880Z 
> now_in_moment = moment(now) // Transform Date object into moment object 
moment("2019-02-19T19:07:25.880") 
> var now_as_date = now_in_moment.toDate() // Transform moment object back to Date object 
> now_as_date 
2019-02-19T11:07:25.880Z 
> now_as_date.constructor.name 
'Date'


Supplement 
* FAQ - How to format a JavaScript date 
* FAQ - Moment.js transform to date object 
* W3CSchool - JavaScript Date Reference 
* npm - moment: A lightweight JavaScript date librar...ulating, and formatting dates. 
# npm install -S moment


2019年2月16日 星期六

[ JS 常見問題 ] How to sort an array of integers correctly

Source From Here 
Question 
Trying to get the highest and lowest value from an array that I know will contain only integers seems to be harder than I thought: 
  1. var numArray = [140000, 104, 99];  
  2. numArray = numArray.sort();  
  3. alert(numArray)  
I'd expect this to show 99, 104, 140000. Instead it shows 104, 140000, 99. So it seems the sort is handling the values as strings. Is there a way to get the sort function to actually sort on integer value? 

How-To 
By default, the sort method sorts elements alphabetically. To sort numerically just add a new method which handles numeric sorts (sortNumber, shown below): 
  1. function sortNumber(a,b) {  
  2.     return a - b;  
  3. }  
  4.       
  5. var numArray = [140000, 104, 99];  
  6. numArray.sort(sortNumber);  
  7. alert(numArray.join(","));  
You can use ES6 arrow functions: 
  1. numArray.sort((a, b) => a - b); // For ascending sort  
  2. numArray.sort((a, b) => b - a); // For descending sort  


[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...