The secret to wholesale...

In the article about buying Thai goods, I introduced wholesale markets and cheap...

Restaurant business and the...

Customers are a special figure in restaurants. This may seem obvious, but...

Guide the clues to...

Japanese goods Known for putting quality first. However, in the past, due...

Online cosmetics business and...

Starting a business, especially online cosmetics business is the silver trend and...
HomeLập trìnhJavaScriptJavaScript Date Now...

JavaScript Date Now – Có thể hiểu được thực tế với JavaScript


Phần lớn các ứng dụng được xây dựng theo xu hướng của algún componente của tipo fecha, ya sea por la creación de la fecha de un recurso, or por una marca temporal (dấu thời gian) de alguna actividad.

Tratar con formatos de fecchas and marcas de tiempo puede puede resultar agotador. En esta guía entrarás cómo getter la fecha de hoy en khác nhau formatos con JavaScript.

Objeto Date (fecha) de JavaScript

JavaScript tiene un objeto Date tích hợp mà almacena la fecha y la hora và chứng minh phương pháp cho manejarlos.

Para crear una nueva instancia del objeto Dateutiliza la palabra clave new :

const fecha = new Date();

phản đối Date liên tục Number(número) que đại diện cho các cuộc chiến quân sự qua các kỷ nguyên (fecha de referencia), que es el 1 de enero de 1970.

Puedes convertir una string al constructor Date để tạo ra một đối tượng với một điều đặc biệt:

const fecha = new Date('Jul 12 2011');

Để có được một làn sóng thực tế, hãy sử dụng phương pháp lập tức getFullYear() không phản đối Date . phương pháp getFullYear() devuelve el año de la fecha especada en el constructor Date

const añoActual = fecha.getFullYear();
console.log(añoActual); //2020

Tương tự, tồn tại các phương thức để nhận được ngày này và ngày khác là thực tế:

const hoy = fecha.getDate();
const mesActual = fecha.getMonth() + 1; 

phương pháp getDate() devuelve el día del mes en el que estamos (1-31).

Đọc thêm  Cách tạo đối tượng trong JavaScript

phương pháp getMonth() devuelve el mes de la fecha especificada. Un punto a tener en cuenta acerca del phương pháp getMonth() es que devuelve valores indexados (0-11) donde el 0 es enero y el el el el el es diciembre. Port tanto, añadiéndole 1 normalizamos el valor del mes.

Ngày bây giờ

now() là một phương pháp xác định đối tượng Date . Devuelve el valor en milisegundos que showa el tiempo transcurrido desde el Epoch. Puedes pasar los milisegundos devueltos del methodo now() trong hàm tạo Date para crear una instancia de un nuevo objeto Date:

const tiempoTranscurrido = Date.now();
const hoy = new Date(tempoTranscurrido);

Định dạngeando Ngày tháng

Các định dạng có thể được lấy từ nhiều định dạng (GMT, ISO, và các định dạng) sử dụng các phương thức đối tượng Date.

phương pháp toDateString() devuelve la fecha en un format por un humano:

hoy.toDateString(); // "Sun Jun 14 2020"

phương pháp toISOString() phát triển phần mở rộng của ISO 8601:

hoy.toISOString(); // "2020-06-13T18:30:00.000Z"

phương pháp toUTCString() devuelve la fecha en el format según la zona horaria UTC:

hoy.toUTCString(); // "Sat, 13 Jun 2020 18:30:00 GMT"

phương pháp toLocaleDateString() devuelve la fecha en un định dạng hợp lý là localización, thích ứng với thành ngữ và định dạng lugar donde te encuentres:

hoy.toLocaleDateString(); // "14/6/2020"

Bạn có thể tham khảo một tài liệu tham khảo hoàn thành phương pháp của phương pháp Date trong tài liệu chính thức của MDN.

Función para formatear a medida la fecha

Ngoài các định dạng mà bạn đề cập đến trong một phần khác của các bản cập nhật, ứng dụng có thể có một định dạng dữ liệu khác. Puede ser en el format yy-dd-mm, yyyy-dd-mm, dd-mm-yy o de cualquier otro.

Đọc thêm  Cách xây dựng Máy tính tiền boa bằng HTML, CSS và JavaScript

Để giải quyết vấn đề này, hãy tạo ra một chức năng có thể tái sử dụng mà bạn có thể sử dụng chức năng cần thiết của tất cả các sản phẩm mới.

Port tanto, en esta sección, vamos a crear una función de utilidad que nos devuelva la fecha en el format que le indiquemos en el tranh luận:

const hoy = new Date();

function formatoFecha(fecha, formato) {
	//
}

formatoFecha(hoy, 'dd/mm/yy');

Necesitas reemplazar las string “dd”, “mm” y “yy” con losrespectivos valores del día, mes y año del format pasado en la string que pasamos en el argumento.

Para hacer eso puedes usar el method replace() como te muestro aquí abajo:

formato.replace('mm', fecha.getMonth() + 1);

Pero esto dará lugar a uncadenamiento de methodos and hard mantenimiento a medida that intentas hacer que la función sea more linh hoạt:

formato.replace('mm', fecha.getMonth() + 1)
    .replace('yy', fecha.getFullYear())
	.replace('dd', fecha.getDate());

Về phương pháp sử dụng phương pháp mã hóa, bạn có thể sử dụng các biểu hiện chính quy của phương pháp đó replace().

Đầu tiên, hãy tạo một đối tượng mà nó đại diện cho một chuỗi con có giá trị bằng cách tôn trọng giá trị của nó:

const formatoMap = {
    dd: fecha.getDate(),
    mm: fecha.getMonth() + 1,
    yy: fecha.getFullYear().toString().slice(-2),
    yyyy: fecha.getFullYear()
};

Después, usa una expresión regular para hacer occicidir y reemplazar las strings:

fechaFormateada = formato.replace(/mm|dd|yy|yyy/gi, matched => map[matched]);

La función completa se ve así:

function formatoFecha(fecha, formato) {
    const map = {
        dd: fecha.getDate(),
        mm: fecha.getMonth() + 1,
        yy: fecha.getFullYear().toString().slice(-2),
        yyyy: fecha.getFullYear()
    }

    return formato.replace(/dd|mm|yy|yyy/gi, matched => map[matched])
}

Puedes también añadir la habilidad de formatear las marcas de tiempo a la función.

Đọc thêm  Cách thức và lý do sử dụng Lập trình chức năng trong JavaScript hiện đại

Phần kết luận

Espero que ahora entiendas mejor el objeto Date de JavaScript. Puedes usar también librerías externas como datejs y moment para manejar fchas en tu ứng dụng.

Hasta la siguiente, cuídate ya por ello.

Traducido del artículo de Vijit Ailhttps://www.freecodecamp.org/news/javascript-date-now-how-to-get-the-current-date-in-javascript/



Zik.vn – Biên dịch & Biên soạn Lại

spot_img

Create a website from scratch

Just drag and drop elements in a page to get started with Newspaper Theme.

Buy Now ⟶

Bài viết liên quang

DMCA.com Protection Status