Example of a simple method for converting JS timestamp to date format

  • 2021-09-12 00:19:24
  • OfStack

Several Methods of Transforming Front-end Time Format into Time Stamp


<script type="text/javascript">
			var date=new Date();
			console.log(date);//Wed Feb 13 2019 11:40:45 GMT+0800 ( China Standard Time )
			// 1: This method is not recommended, and millisecond values are converted to 000
			var timeStamp1=Date.parse(date);
			console.log(timeStamp1);//1550029245000
			// 2: Pass valueOf() Function returns the original value of the specified object to get the exact timestamp value 
			var timeStamp2=date.valueOf();
			console.log(timeStamp2);//1550029245434
			// 3: The millisecond value of the current time is directly obtained by prototype method, which is accurate 
			var timeStamp3=date.getTime();
			console.log(timeStamp3);//1550029245434
			// 4: Convert time into 1 A number A numeric value of type, that is, a timestamp 
			var timeStamp4=Number(date);
			console.log(timeStamp4);//1550029245434
		</script>

JS and jQuery have been used for a period of time, and recently found that they do not have their own timestamp formatting functions, so they integrated the relevant timestamp formatting functions on the Internet and wrote a timestamp formatting function DateToTime, which provides a variety of formatting styles:

Y-m-d, Y-m-d H: i: s, Y/m/d, Y/m/d H: i: s, Y, m, d, Y, m, H: i: s

The time here is sometimes only entered Y-m-d H: i is also available


/**
 * [TimeToDate Convert timestamp to date ]
 * @param {[type]} unixTime [ Time stamp ]
 * @param {String} type     [Y-m-d,Y-m-d H:i:s,Y/m/d,Y/m/d H:i:s,Y Year m Month d Day ,Y Year m Month d Day  H:i:s]
 */
function TimeToDate(unixTime,type="Y-M-D H:i:s"){
    var date = new Date(unixTime * 1000);// The timestamp is 10 Position requirement *1000 With a timestamp of 13 You don't need to multiply if you are a bit 1000
    var datetime = "";
    datetime += date.getFullYear() + type.substring(1,2);
    datetime += (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + type.substring(3,4);
    datetime += (date.getDate() < 10 ? '0'+(date.getDate()) : date.getDate());
    if (type.substring(5,6)) {
        if (type.substring(5,6).charCodeAt() > 255) {
            datetime += type.substring(5,6);
            if (type.substring(7,8)) {
                datetime += " " + (date.getHours() < 10 ? '0'+(date.getHours()) : date.getHours());
                if (type.substring(9,10)) {
                    datetime += type.substring(8,9) + (date.getMinutes() < 10 ? '0'+(date.getMinutes()) : date.getMinutes());
                    if (type.substring(11,12)) {
                        datetime += type.substring(10,11) + (date.getSeconds() < 10 ? '0'+(date.getSeconds()) : date.getSeconds());
                    };
                };
            };
        }else{
            datetime += " " + (date.getHours() < 10 ? '0'+(date.getHours()) : date.getHours());
            if (type.substring(8,9)) {
                datetime += type.substring(7,8) + (date.getMinutes() < 10 ? '0'+(date.getMinutes()) : date.getMinutes());
                if (type.substring(10,11)) {
                    datetime += type.substring(9,10) + (date.getSeconds() < 10 ? '0'+(date.getSeconds()) : date.getSeconds());
                };
            };
        };
    };
    return datetime;
}

TimeToDate("1515640111");    //2018-01-11 11:08:31
TimeToDate("1515640111","Y-m-d");    //2018-01-11
TimeToDate("1515640111","Y-m-d H:i");    //2018-01-11 11:08
TimeToDate("1515640111","Y-m-d H:i:s");    //2018-01-11 11:08:31
TimeToDate("1515640111","Y/m/d");    //2018/01/11
TimeToDate("1515640111","Y/m/d H:i:s");    //2018/01/11 11:08:31
TimeToDate("1515640111","Y Year m Month d Day ");    //2018 Year 01 Month 11 Day 
TimeToDate("1515640111","Y Year m Month d Day  H:i:s");    //2018 Year 01 Month 11 Day  11:08:31

/**
 * [DateToTime  Date conversion timestamp ]
 * @param {[type]} day [ Date format, only standard format is supported ]
 */
function DateToTime(day){
	// re = /(\d{4})(?:-(\d{1,2})(?:-(\d{1,2}))?)?(?:\s+(\d{1,2}):(\d{1,2}):(\d{1,2}))?/.exec(day); //  Original 
	re = /(\d{4})(?:\D?(\d{1,2})(?:\D?(\d{1,2}))?[^\d\s]?)?(?:\s+(\d{1,2})\D?(\d{1,2})\D?(\d{1,2}))?/.exec(day);
	return new Date(re[1],(re[2]||1)-1,re[3]||1,re[4]||0,re[5]||0,re[6]||0).getTime()/1000;
}
DateToTime("2018-01-11 11:08:31");
DateToTime("2018-01-11");
DateToTime("2018 Year 01 Month 11 Day  11 Hour 08 Points 31 Seconds ");
DateToTime("2018");

Supplementary timestamp and date conversion:


function TimeToDate(date,format) {
 format = format || 'YYYY-MM-DD hh:mm:ss';
 var dateTest = (/^(-)?\d{1,10}$/.test(date) || /^(-)?\d{1,13}$/.test(date));
 if(/^[1-9]*[1-9][0-9]*$/.test(date) && dateTest){
  var vdate = parseInt(date);
  if (/^(-)?\d{1,10}$/.test(vdate)) {
   vdate = vdate * 1000;
  } else if (/^(-)?\d{1,13}$/.test(vdate)) {
   vdate = vdate * 1000;
  } else if (/^(-)?\d{1,14}$/.test(vdate)) {
   vdate = vdate * 100;
  } else {
   alert(" The timestamp is not formatted correctly ");
   return;
  }
  var setdate = new Date(vdate);
  return parse({YYYY:setdate.getFullYear(), MM:digit(setdate.getMonth()+1), DD:digit(setdate.getDate()) , hh:digit(setdate.getHours()), mm:digit(setdate.getMinutes()), ss:digit(setdate.getSeconds()) }, format);
 }else {
  // Convert a date to a timestamp 
  var arrs = date.match(/\w+|d+/g),
   newdate = new Date(arrs[0],parseInt(arrs[1])-1,arrs[2],arrs[3]||0,arrs[4]||0,arrs[5]||0),
   timeStr = Math.round(newdate.getTime() / 1000);
  return timeStr;
 }

 function parse(ymdhms, format) {
  var regymdzz = "YYYY|MM|DD|hh|mm|ss|zz";
  return format.replace(new RegExp(regymdzz,"g"), function(str, index) {
   return str == "zz" ? "00":digit(ymdhms[str]);
  });
 };
 function digit(num) {
  return num < 10 ? "0" + (num | 0) :num;
 };
};

Summarize


Related articles: