11 Nov 2022

Get DateTime as a Formatted String in Matlab

收藏到CSDN网摘

A very common task would be obtain the current timestamp while writing code in any programming languages, especially for logging and debugging purpose. Almost all the languages provide support for retrieving the current date and time using either built-in or 3rd party libs. 

Matlab has some built-in formats already. All we need to do is to pass the proper format number to its 'datestr()' function. To obtain the current time and date, 'now' can be passed to the 'datestr()' function as the first parameter. The 2nd parameter is for specifying the format. Someone may write code like "datestr(now, 'yyyy-mm-dd HH:MM:SS')" to get a timestamp such as 2022-11-10 00:00:42. However, apart from explicitely writing out the format string, Matlab also supports specifying the format using a single number - "datestr(now, 31)" will give you the same result. How about other formats? All the formats are saved in the 'datestr.m', which can be accessed by right-clicking on the function and 'open ...'. Then, a list of the format numbers can be found there.
switch dateform
    case -1, formatstr = 'dd-mmm-yyyy HH:MM:SS';
    case 0,  formatstr = 'dd-mmm-yyyy HH:MM:SS';
    case 1,  formatstr = 'dd-mmm-yyyy';
    case 2,  formatstr = 'mm/dd/yy';
    case 3,  formatstr = 'mmm';
    case 4,  formatstr = 'm';
    case 5,  formatstr = 'mm';
    case 6,  formatstr = 'mm/dd';
    case 7,  formatstr = 'dd';
    case 8,  formatstr = 'ddd';
    case 9,  formatstr = 'd';
    case 10, formatstr = 'yyyy';
    case 11, formatstr = 'yy';
    case 12, formatstr = 'mmmyy';
    case 13, formatstr = 'HH:MM:SS';
    case 14, formatstr = 'HH:MM:SS PM';
    case 15, formatstr = 'HH:MM';
    case 16, formatstr = 'HH:MM PM';
    case 17, formatstr = 'QQ-YY';
    case 18, formatstr = 'QQ';
    case 19, formatstr = 'dd/mm';
    case 20, formatstr = 'dd/mm/yy';
    case 21, formatstr = 'mmm.dd,yyyy HH:MM:SS';
    case 22, formatstr = 'mmm.dd,yyyy';
    case 23, formatstr = 'mm/dd/yyyy';
    case 24, formatstr = 'dd/mm/yyyy';
    case 25, formatstr = 'yy/mm/dd';
    case 26, formatstr = 'yyyy/mm/dd';
    case 27, formatstr = 'QQ-YYYY';
    case 28, formatstr = 'mmmyyyy';
    case 29, formatstr = 'yyyy-mm-dd';
    case 30, formatstr = 'yyyymmddTHHMMSS';
    case 31, formatstr = 'yyyy-mm-dd HH:MM:SS';

No comments :

Post a Comment