2

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');

but:

DIR1{1} = 26/06/1998
DIR2{1} = 15:00:00

DIR4{1} = 17/03/0049 15:00:00

What's happened?

2 Answers 2

1

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

The fix is rather easy: just don't use strcat, but rather use plain matrix concatenation:

strSrcDate = ['26/06/1998',' ','15:00:00']

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:

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
Sign up to request clarification or add additional context in comments.

Comments

0

The input to datestr must be a vector.

date(1,:)=[1998 6 26 15 0 0];
Sdate{1}=datestr(date,'dd/mm/yyyy HH:MM:SS');

Sdate =

26/06/1998 15:00:00

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.