필터 지우기
필터 지우기

How to convert date variable with varying length?

조회 수: 3 (최근 30일)
aaron Harvey
aaron Harvey 2016년 2월 12일
댓글: aaron Harvey 2016년 2월 13일
Hi there, I have a date variable with thousands of dates in the format mmddyy i would like to convert it to a yyyymmdd format. A problem i am having is whenever the month is bellow 10 the 0 is missing e.g. rather than reading 012988 it reads 12988. Thank-you
  댓글 수: 1
Fangjun Jiang
Fangjun Jiang 2016년 2월 12일
where is your source data come from, a text file, or already stored in a matrix, in what format?

댓글을 달려면 로그인하십시오.

채택된 답변

Jan
Jan 2016년 2월 13일
I'd avoud the time consuming indirection over CHAR strings, but convert the doubles directly:
d = [120316, 12988];
year = rem(d, 100);
day = rem(floor(d / 100), 100);
month = rem(floor(d / 10000), 100);
% Decide how to convert the 2 digits year to a 4 digits year:
year = 1900 + year + 100 * (year < 1960);
result = year * 10000 + month * 100 + day;

추가 답변 (2개)

Matthew Eicholtz
Matthew Eicholtz 2016년 2월 12일
If your data is stored in a cell array, such as
d = {'21216','112515','91101','122515','70487'}; %random dates in mmddyy format (with leading '0' missing)
then add the leading '0' to months Jan-Sep,
d = cellfun(@(x) sprintf('%06s',x),d,'uni',0)
and use the built-in date functions to convert to the desired format,
newdates = num2cell(datestr(datenum(d,'mmddyy'),'yyyymmdd'),2);
  댓글 수: 2
aaron Harvey
aaron Harvey 2016년 2월 13일
Thank-you for the reply, I have tried your code and a few slight adjustments as well but with no success.
HOT.date = cellfun(@(x) sprintf('%06s',x),HOT.date,'uni',0);
HOT.date = datestr(datenum(num2str(HOT.date(i)),'mmddyy'),'yyyymmdd');
Where HOT.date is my variable. I think its not working as my dates are in a double not a cell array, i would preferably like to keep them as a double as well as all the corresponding variables are, but i don't have enough MATLAB know-how to know how.
Jan
Jan 2016년 2월 13일
@Aaron: You see that it would have been useful to post some example data in the question to clarify the type.

댓글을 달려면 로그인하십시오.


Azzi Abdelmalek
Azzi Abdelmalek 2016년 2월 12일
You have to indicate the format of your data. Suppose your data are like below:
d=[12988 112589 52214]
e=arrayfun(@(x) num2str(x),d,'un',0)
f=cellfun(@(x) [num2str(zeros(1,6-numel(x))) x],e,'un',0)
out=cellfun(@(x) datestr(datenum(x,'mmddyy'),'yyyymmdd'),f,'un',0)

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by