Programming language developed by Netscape for improving websites. Execute on the client workstation. Javascript is an object-oriented scripting language mainly used in xHTML pages.





Site user blocks : Account info / user rights / summary

Exemple d'utilisation de la fonction Date de javascript

Convertit une date type datetime en timestamp unix.

Informations :

Dates
  • Publish : : Monday 23 january 2023

  • 13 views

Share :

Bonjour, je viens de m’apercevoir qu'en JavaScript les mois, les heures, les minutes et les secondes sont sur qu'un seul chiffre (jusqu'à 9). Et pire, les mois commencent à 0 et finissent à 11.

Pour infos, j'essayais de récupérer/créer le "timestamp" comme en PHP.

J'ai une page sur laquelle est affichée une date à chaque article, et je souhaitais récupérer/créer le timestamp - j'avais 1 mois d'écars ou 50 milles ans de décallage.

Je vous met donc, rapidement ce que j'ai fais :

Script avec 127 lignes


001<script type="text/javascript">
002/******
003 * JavaScript
004 *
005 * Convertit une date type datetime (donc qui vient de SQL)
006 * -> datetime to timestamp unix
007 *
008 **/
009function mk_time(date_format_mysql) {
010
011	var year = date_format_mysql.substr(0,4);
012	var month = date_format_mysql.substr(5,2);
013	var month = month - 1; // because in js 12 (december) do not exist (0-11) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
014	/* Who has already seen in a calendar 0 for the month of January and 11 for December. Again for the days of the week (weekday) 0-6 ok but for the number of a month its strong... */
015	var day = date_format_mysql.substr(8,2);
016	var hour = date_format_mysql.substr(11,2);
017	var min = date_format_mysql.substr(14,2);
018	var sec = date_format_mysql.substr(17,2);
019
020/*
021	// Je laisse cette facon.. :/
022	// si pour quelques raisons le formatage "date_format_mysql" ne serait pas.
023	// exemple : 2023-1-23 3:6:41
024	
025	var dateMysqlArray = date_format_mysql.split(" ");
026	var dateFull = dateMysqlArray[0];
027	var hourFull = dateMysqlArray[1];
028
029	var dateArray = dateFull.split("-");
030	var year = dateArray[0];
031	var month = dateArray[1];
032	var day = dateArray[2];
033
034	var hourArray = hourFull.split(":");
035	var hour = hourArray[0];
036	var min = hourArray[1];
037	var sec = hourArray[2];
038*/	
039//	return year+'-'+month+'-'+day+' '+hour+':'+min+':'+sec;
040
041	a = new Date();
042
043	a.setYear(year);
044	a.setMonth(month);
045	a.setDate(day);
046	a.setHours(hour);
047	a.setMinutes(min);
048	a.setSeconds(sec);
049
050	return a.getTime()/1000;
051	//return Math.floor(a.getTime()/1000);
052
053}
054
055/******
056 * JavaScript
057 *
058 * Pour l'affichage en date type datetime
059 * -> date JS to datetime
060 *
061 **/
062function date_transform_number(number, type) {
063	if(type == 'month') {
064		/*const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];*/
065		const months = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];
066		nbr = months[number];
067	}
068	if(type == 'day' || type == 'hour' || type == 'min' || type == 'sec') {
069		nbr = number < 10 ? '0'+number : number;
070	}
071	return nbr;
072}
073
074//--------------------------------------------
075// just for info current date
076//--------------------------------------------
077var dateClass = new Date();
078
079var time = dateClass.getTime();
080var now = Date.now();
081
082var year = dateClass.getFullYear();
083var month = dateClass.getMonth();
084//var month = date_transform_number(month, 'month');
085var weekday = dateClass.getDay(); // (0-6)
086var day = dateClass.getDate();
087//var day = date_transform_number(day, 'day');
088var hour = dateClass.getHours();
089//var hour = date_transform_number(hour, 'hour');
090var min = dateClass.getMinutes();
091//var min = date_transform_number(min, 'min');
092var sec = dateClass.getSeconds();
093//var sec = date_transform_number(sec, 'sec');
094
095console.log('time: '+time+' -> '+typeof time);
096console.log('now: '+now+' -> '+typeof now);
097console.log('date: '+year+'-'+month+'-'+day+' '+hour+':'+min+':'+sec);
098
099//--------------------------------------------
100
101
102//--------------------------------------------
103// Well...
104//--------------------------------------------
105console.log('\n');
106
107var text_content = '2022-12-14 01:00:00';
108console.log('text_content: '+text_content+' -> '+typeof text_content);
109
110// Ma fonction.... il y avait un mois de décalage ;)
111var timestamp_content = mk_time(text_content);
112console.log('timestamp_content: '+timestamp_content+' -> '+typeof text_content);
113
114var date_content = new Date(timestamp_content * 1000);
115console.log('date_content: '+date_content+' -> '+typeof date_content);
116
117//var timestamp_content_2 = Math.floor(date_content);
118//console.log('timestamp_content_2: '+timestamp_content_2+' -> '+typeof timestamp_content_2);
119
120//var timestamp_content_3 = timestamp_content.substr(-4);
121//console.log('timestamp_content_4: '+timestamp_content_3+' -> '+typeof timestamp_content_3); // ???
122
123//var timestamp_content_4 = timestamp_content.split(".");
124//console.log('timestamp_content_3: '+timestamp_content_4[0]+' -> '+typeof timestamp_content_4[0]); // ???
125
126//--------------------------------------------
127</script>

Cà nous affiche la bonne date dans la console firefox/chrome (F12) sur la ligne "date_content" :

Script avec 8 lignes

001time: 1674442484360 -> number
002now: 1674442484360 -> number
003date: 2023-0-23 3:54:44
004
005text content: 2022-12-14 01:00:00 -> string
006timestamp_content: 1670976000.363 -> string
007date_content: Wed Dec 14 2022 01:00:00 GMT+0100 (heure normale d’Europe centrale) -> object
008timestamp_content_2: 1670976000363 -> number

En PHP :

Script avec 35 lignes

001<?php
002/******
003 * PHP
004 *
005 * Convertit une date type datetime
006 * -> datetime to timestamp unix
007 *
008 **/
009function mk_time($date_format_mysql) {
010
011    $year = substr($dateTime2mysql,0,4);
012    $month = substr($dateTime2mysql,5,2);
013    $day = substr($dateTime2mysql,8,2);
014    $hour = substr($dateTime2mysql,11,2);
015    $min = substr($dateTime2mysql,14,2);
016    $sec = substr($dateTime2mysql,17,2);
017
018    return mktime($hour, $min, $sec, $month, $day, $year);
019}
020
021$date_text = '2022-12-14 01:00:00';
022
023$time_php_test = mk_time($date_text);
024$date_php = date('Y-m-d H:i:s', $time_php_test);
025
026// old value sans enlever "-1" du mois d'une date PHP
027$time_js_test = '1673654400';
028$date_js = date('Y-m-d H:i:s', $time_js_test);
029
030echo 'Date PHP OK : '.$time_php_test.' -> '.$date_php.'<br />';
031echo 'Date PHP NOK : '.$time_js_test.' -> '.$date_js.'<br />';
032    
033// Date PHP OK : 1670976000 -> 2022-12-14 01:00:00
034// Date PHP NOK : 1673654400 -> 2023-01-14 01:00:00
035

Voilà :)

Salutations,
Romain






Author of the page

O.Romain.Jaillet-ramey

O.Romain.Jaillet-ramey

  • Firstname : Olivier Romain Luc
  • Lastname : : Jaillet-ramey
  • Arrived on tuesday 19 october 1976 (1976/10/19 00:00)
    46 years activity !

Translate this page with Google

Firefox Nighlty

Our friends from Framasoft are interested in Mozilla and asked them questions about Nightly: Firefox Night-club, free entry !






Valid XHTML 1.0 Strict CSS Valide !

ipv6 ready