diff m-toolbox/classes/@time/parse.m @ 0:f0afece42f48

Import.
author Daniele Nicolodi <nicolodi@science.unitn.it>
date Wed, 23 Nov 2011 19:22:13 +0100
parents
children
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/m-toolbox/classes/@time/parse.m	Wed Nov 23 19:22:13 2011 +0100
@@ -0,0 +1,69 @@
+function msec = parse(str, format, timezone)
+  
+  % second and third arguments are optional
+  if nargin < 3
+    timezone = '';
+  end
+  if nargin < 2
+    format = '';
+  end
+  
+  % default timezone
+  if isempty(timezone)
+    timezone = time.timezone;
+  end
+  % convert string timezone into java object 
+  if ischar(timezone)
+    timezone = java.util.TimeZone.getTimeZone(timezone);
+  end
+  
+  % obtain a java time format description to use for parsing
+  if isempty(format)
+    % infere it from the string
+    format = parse_time_string(str);
+  else
+    % convert a given MATLAB time format into a Java one
+    format = time.matfrmt2javafrmt(format);
+  end
+  
+  % parse the string accordingly to the corrent format and timezone
+  tformat = java.text.SimpleDateFormat(format, java.util.Locale.UK);
+  tformat.setTimeZone(timezone);
+  try
+    % It is necessary to replace 'GMT+03' by 'GMT+03:00' because java
+    % expects the ':00' at the end.
+    str = regexprep(str, '([gG][mM][tT][+-]\d\d?$)', '$1:00');
+    msec = tformat.parse(str).getTime();
+  catch
+    error('### unable to parse time string ''%s'' accordingly to format ''%s''', str, format);
+  end
+  
+end
+
+
+function str = parse_time_string(str)
+
+  % supported patterns
+  parse = { '\s[gG][mM][tT][+-]?\d\d?$',      ' z';      ... % GMT+1 or GMT+12
+            '\s[gG][mM][tT][+-]?\d\d?:\d\d$', ' z';      ... % GMT+08:12
+            '\s\w{3}$',                       ' z';      ... % PST
+            '\s[+-]\d{4}$',                   ' Z';      ... % +0800
+            '\d{2}:\d{2}:\d{2}',              'HH:mm:ss';    ...
+            '\d{2}:\d{2}',                    'mm:ss';       ...
+            '\d{2} \w{3} \d{4}',              'dd MMM yyyy'; ...
+            '\d{2}-\w{3}-\d{4}',              'dd-MMM-yyyy'; ...
+            '\d{2}.\w{3}.\d{4}',              'dd.MMM.yyyy'; ...
+            '\d{2}-\d{2}-\d{4}',              'dd-MM-yyyy';  ...
+            '\d{2}\.\d{2}\.\d{4}',            'dd.MM.yyyy';  ...
+            '\d{4}-\d{2}-\d{2}',              'yyyy-MM-dd';  ...
+            '\d{4}\.\d{2}\.\d{2}',            'yyyy.MM.dd';  ...
+            '\d{2}-\d{2}',                    'MM-dd';       ...
+            '\.\d{1,3}',                      '.SSS'};
+            
+  % try to match the patterns to the string and replace
+  % it with the corresponding Java time format descriptor
+  re   = parse(:,1);
+  frmt = parse(:,2);
+  str  = regexprep(str, re, frmt);
+  
+end