Matlab中多个字符串的日期 [英] Date from multiple strings in Matlab
问题描述
我必须从两个字符串中生成一个日期(字符串或数字),第一个是日期,第二个是时间.我一定在代码中犯了一些错误,因为结果与源数据的串联不同.
I have to generate one date (string or number) from two strings, the first of which is the day and the second the time. I must have made an error something in my code, because the result is different from the concatenation of the source data.
DIR4{h} = datestr(strcat(DIR1{h},' ',DIR2{h}),'dd/mm/yyyy HH:MM:SS');
但是:
DIR1{1} = 26/06/1998
DIR2{1} = 15:00:00
DIR4{1} = 17/03/0049 15:00:00
发生了什么事?
推荐答案
如果执行了每个中间步骤,您会发现strcat
会忽略尾随空格(
If you'd executed every intermediate steps, you would have seen that strcat
ignores trailing spaces (as documented):
strcat('26/06/1998',' ','15:00:00')
> 26/06/199815:00:00
修复非常简单:只是不使用strcat
,而是使用纯矩阵级联:
The fix is rather easy: just don't use strcat
, but rather use plain matrix concatenation:
strSrcDate = ['26/06/1998',' ','15:00:00']
接下来,您将使用错误的日期转换功能. datestr
是要转换字符串,而不是源字符串.好的,它可以处理字符串输入,但这相当受限制 .您将要使用 datenum :
Next you're using the wrong date conversion function. datestr
is to convert tó a string, not from. Ok ok, it can handle string input, but that's quite restricted. You'll want to use datenum:
这给出了一个日期序列号(请阅读文档!),它是一个代表日期的数字(没有任何歧义).使用该编号来内部存储日期,并且要将日期打印到屏幕或文件中时,请使用datestr
:
This gives a date serial (read the doc!), which is a number that represents a date (without any ambiguity). Use that number for internal storage of a date, and when you want to print that date out to screen or file, convert it to a string using datestr
:
numSrcDate = datenum(strSrcDate,'dd/mm/yyyy HH:MM:SS')
> 729932.625
datestr(numSrcDate,'dd/mm/yyyy HH:MM:SS'); % or any other format
datestr(numSrcDate,'dd/mm/yy HH:MM');
> 26/06/1998 15:00:00
> 26/06/98 15:00
这篇关于Matlab中多个字符串的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!