Check the format of a string.
Mostra commenti meno recenti
I have a string variable and I need to check if it is of the given format. Its actually a date time. There are two types.
One is '20240109_153535' and I need to confirm this is 'yyyyMMdd_HHmmss'.
And other is '2023-08-15T06:10:09.89' and I need to confirm this is 'yyyy-MM-dd''T''HH:mm:ss.SSS'
How do I do that? Thank you. Thank You.
Risposta accettata
Più risposte (1)
VINAYAK LUHA
il 10 Gen 2024
Hi Govind,
Apparently, you have datetime of different formats and want to assert that a particular datetime is in a particular format. Besides having the option to do regex checking on the string converted datetime, you can also leverage the "try" block to try to obtain a particular datetime in a particular format and asset accordingly.
Refer to the below code snippet for an example.
str1 = '20240109_153535';
str2 = '2023-08-15T06:10:09.89';
format = assertDateTimeFormat(str1)
format = assertDateTimeFormat(str2)
function df = assertDateTimeFormat(str)
f1 = 'yyyyMMdd_HHmmss';
f2 = 'yyyy-MM-dd''T''HH:mm:ss.SSS';
try
datetime(str, 'InputFormat', f1);
df ="in yyyyMMdd_HHmmss Format";
return
end
try
datetime(str, 'InputFormat', f2);
df='in yyyy-MM-dd''T''HH:mm:ss.SSS';
return
end
end
Hope this answers your query.
Regards,
Vinayak Luha
Categorie
Scopri di più su String Parsing in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!