簡體   English   中英

如何根據SQL DATE數據類型計算用戶年齡

[英]How can I calculate the user Age based on a sql DATE datatype

因此,從我的SQL查詢中,我收到:FRI DEC 13 1991 00:00:00 GMT + 0100(CET)作為日期結果。 但是我想要的只是當前的用戶年齡(以年為單位)。 反正有計算嗎? 還是我可以使用任何標稱擴展名? 謝謝你的時間。

您可以像這樣使用Javascript Date對象:

var sqlDate = new Date('FRI DEC 13 1991 00:00:00 GMT+0100 (CET)');
//log year
console.log(sqlDate.getFullYear());
var intPersonYOB = sqlDate.getFullYear()

要對year ,您可以創建一個新的Date對象,並按以下方式獲取當前年,以便對其進行一些數學運算:

var currentDate = new Date();
var currentYear = currentDate.getFullYear();
var intPersonAge = currentYear - intPersonYOB;
console.log(intPersonAge);`

這足以讓他變老

SELECT DATEDIFF(day,'olddate','recentdate') AS AGE FROM your_table;

返回值是AGE。 使用任何日期格式,但這是您問題的SQL查詢

下面的函數將根據您的字符串返回年齡。 您可以使用相同的方法。

ar str = 'FRI DEC 13 1991 00:00:00 GMT+0100 (CET)';

age = getAge(str);

function getAge(str) {
  var matches = str.match(/[a-z]{3} ([a-z]{3}) (\d{1,2}) (\d{4})/i);
  str = matches[3] + '-';
  switch (matches[1]) {
    case 'JAN':
      str += '01-';
      break;
    case 'FEB':
      str += '02-';
      break;
    case 'MAR':
      str += '03-';
      break;
    case 'APR':
      str += '04-';
      break;
    case 'MAY':
      str += '05-';
      break;
    case 'JUN':
      str += '06-';
      break;
    case 'JUL':
      str += '07-';
      break;
    case 'AUG':
      str += '08-';
      break;
    case 'SEP':
      str += '09-';
      break;
    case 'OCT':
      str += '10-';
      break;
    case 'NOV':
      str += '11-';
      break;
    case 'DEC':
      str += '12-';
      break;
  }
  str += parseInt(matches[2]) < 10 ? '0' + matches[2] : matches[2];
  var birthDate = new Date(str);
  var nowDate = new Date();
  return nowDate.getFullYear() - 1 - birthDate.getFullYear() + (
      birthDate.getMonth() < nowDate.getMonth() ? 1 :
        birthDate.getMonth() == nowDate.getMonth() ? 
          birthDate.getDate() <= nowDate.getDate()   ? 1 : 0
        : 0  
    );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM