ค้นหาเว็บไซต์

javascript - วิธีการต่อสตริงและตัวเลขใน Typescript


ฉันกำลังใช้วิธีเพื่อดึงข้อมูล

function date() {
    let str = '';

    const currentTime = new Date();
    const year = currentTime.getFullYear();
    const month = currentTime.getMonth();
    const day = currentTime.getDate();

    const hours = currentTime.getHours();
    let minutes = currentTime.getMinutes();
    let seconds = currentTime.getSeconds();
    if (month < 10) {
        //month = '0' + month;
    }
    if (minutes < 10) {
        //minutes = '0' + minutes;
    }
    if (seconds < 10) {
        //seconds = '0' + seconds;
    }
    str += year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds + ' ';

    console.log(str);
}

และเมื่อเป็นผลลัพธ์ฉันได้

2017-6-13 20:36:6 

ฉันอยากได้เหมือนกัน แต่แบบ

2017-06-13 20:36:06 

แต่ถ้าฉันลองใช้หนึ่งในบรรทัดที่ฉันคอมเมนต์ไว้ เช่น บรรทัดนี้

month = '0' + month;

ฉันได้รับข้อผิดพลาด

Argument of type 'string' is not assignable to parameter of type 'number'.

ฉันจะรวมสตริงและตัวเลขเข้าด้วยกันได้อย่างไร?

คำตอบ #1

ประเภทยูเนียน

คุณสามารถใช้ประเภทสหภาพเมื่อประกาศตัวแปรได้

let month: string | number = currentTime.getMonth();

if (month < 10) {
  month = '0' + month;
}

เทมเพลตลิเทอรัล (ES6+)

อีกทางหนึ่งคุณสามารถสร้างตัวแปรใหม่และใช้ template literal

const paddedMonth: string = `0${month}`;

การเชื่อมสตริงของคุณจะกลายเป็นแบบนี้ ตัวอย่างเช่น:

str = `${year}-${paddedMonth}-${day} ${hours}:${minutes}:${seconds} `;

อ่านง่ายกว่ามาก ในความเห็นของฉัน

คำตอบ #2

ถ้าคุณต้องการทำงานกับวันที่ คุณสามารถใช้โมดูล momentjs ได้ที่: https://momentjs.com

moment().format('MMMM Do YYYY, h:mm:ss a'); // July 13th 2017, 11:18:05 pm
moment().format('dddd');                    // Thursday
moment().format("MMM Do YY");               // Jul 13th 17
moment().format('YYYY [escaped] YYYY');     // 2017 escaped 2017
moment().format();                          // 2017-07-13T23:18:05+04:30

และเกี่ยวกับข้อผิดพลาดที่คุณได้รับ คุณควรใช้แบบนี้:

 let monthStr: string = month;
 if ( month < 10) {
     monthStr = '0' + month;
 }

บทความที่เกี่ยวข้อง