Conversion of dates to a different format

6 ビュー (過去 30 日間)
Damith
Damith 2015 年 10 月 6 日
コメント済み: Damith 2015 年 10 月 7 日
Hi,
I need to convert 20110530 (2011 May 30) to 2011150 (which is the 150th day since January 01, 2011). How can i perform this task in MATLAB?

採用された回答

Star Strider
Star Strider 2015 年 10 月 6 日
編集済み: Star Strider 2015 年 10 月 6 日
The new date and time functions probably have built-in functions to do what you want, but in their absence, this works:
t_str = '20110530';
dn = datenum('20110530', 'yyyymmdd');
dnstart = datenum(dt_str(1:4), 'yyyy'); % Start Of 2011
dayofyear = dn-dnstart+1
Result = sprintf('%4s%03d', dt_str(1:4),dayofyear)
Result =
2011150
The +1 is necessary for ‘dayofyear’ because it computes the difference between 01-Jan-2011 and doesn’t include 01-Jan-2011.
EDIT — Added ‘Result’ assignment.
  4 件のコメント
Damith
Damith 2015 年 10 月 6 日
Thanks again.
Star Strider
Star Strider 2015 年 10 月 6 日
As always, my pleasure.

サインインしてコメントする。

その他の回答 (2 件)

Peter Perkins
Peter Perkins 2015 年 10 月 7 日
In R2014b or later, use datetime.
Convert a yyyyMMdd string to a datetime:
>> d = datetime('20110530','Format','yyyyMMdd')
d =
20110530
Change its display format to show day of year:
>> d.Format = 'yyyyDDD' % includes a leading zero for dates before 10 Apr
d =
2011150
Get the day of year as a number:
>> day(d,'dayofyear')
ans =
150
Convert to string (though you likely don't need to do this unless you're exporting to outside of MATLAB):
>> char(d) % or use cellstr for multiple dates
ans =
2011150
Convert a number in yyyyMMdd format to a datetime:
>> d = datetime(20110530,'ConvertFrom','yyyyMMdd')
d =
30-May-2011 00:00:00
  1 件のコメント
Damith
Damith 2015 年 10 月 7 日
Thanks.

サインインしてコメントする。


Stephen23
Stephen23 2015 年 10 月 6 日
This is very easy using my FEX submissions datenum8601 and datestr8601:
>> X = datenum8601('20110530');
>> datestr8601(X,'yn')
ans =
2011150
  1 件のコメント
Damith
Damith 2015 年 10 月 6 日
Thanks and appreciate it.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeDates and Time についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by