Finding time and date with Regular Expression (RegEx) in Dart language - regex

I'm writing an application with Flutter. I read the times and dates from a source. The date and time format string sent by the resource is:
(Day, Month, Year, Hour, Minute, Second)
07.04.2021 13:30:00
03.04.2021 11:30:00
04.04.2021 17:30:00
03.04.2021 17:30:00
I want to convert this date and time format to DateTime data type with DateTime.parse() function. Here are some examples of what this function accepts as strings and what I need:
"2012-02-27 13:27:00"
"20120227 13:27:00"
"20120227T132700"
I have to convert the string type data coming to me from the source into one of these formats. But in Dart language I couldn't create the Regular Expression needed to do this and couldn't find it anywhere.
I would be very grateful if anyeone could help me understand what I should do.

If you have to play a lot with the dates, you could use the Jiffy package to ease your development.
DateTime yourDatetime = Jiffy("07.04.2021 13:30:00", "dd.MM.yyyy hh:mm:ss").dateTime;

This is a piece a cake by using regular expressions:
var regExp = RegExp(r'(\d{4}-?\d\d-?\d\d(\s|T)\d\d:?\d\d:?\d\d)');

use DateFormat.parse and DateFormat.format from intl package:
https://api.flutter.dev/flutter/intl/DateFormat/parse.html
https://api.flutter.dev/flutter/intl/DateFormat/format.html
final date = DateFormat("yyyy.MM.dd HH:mm:ss").parse("07.04.2021 13:30:00");
DateFormat("yyyy-MM-dd HH:mm:ss").format(date);
DateTime.parse accepts only a subset of ISO 8601 formats: https://api.flutter.dev/flutter/dart-core/DateTime/parse.html

Related

NiFi toDate() Function altering the content

i have been trying to convert a string to date using
${test:toString():toDate('dd-MMM-yy HH.mm.ss.SSSSSSSSS'):format('dd-MMM-yy HH.mm.ss.SSSSSSSSS')}
my value for test attribute is like 13-MAR-20 15.50.41.396000000
when i'm using the above mentioned expression to convert the string to Date, it actually is changing the date as below:
test (input value):
13-MAR-20 15.50.41.396000000
time (output value)
18-Mar-20 05.50.41.000000000
please advise!
I ran into a similar issue with date time encoded in ISO 8601.
The problem is, that the digits after the second are defined as fragment of a second, not milliseconds. If it has 3 digits, it equivalent to milliseconds. If more than 3, the toDate() function parse the fragment of a second as milliseconds. In your case 396000000 milliseconds = 4,58333333 days.
I solved my issue with replaceAll() by cutting digits to first 3.
${test:replaceAll('(\.[0-9]{3})([0-9]+)','$1')}
But my value was formatted as 18-06-20T05:50:41.396000000, so maybe you have to adjust the regex.

Google Sheet formula to convert Youtube's API ISO 8601 duration format

I have a google sheet script that fetches youtube's video durations. The problem is the time data is in the ISO 8601 format.
For example:
PT3M23S
The formula I'm using right now does a good job converting this into a more readable format.
=iferror(REGEXREPLACE(getYoutubeTime(B20),"(PT)(\d+)M(\d+)S","$2:$3"))
It converts the above into a more readable format 3:23
Now the issue at hand is if the duration of the video is exactly 3 minutes or if the video is shorter than 1 minute regexreplace doesn't reformat it.
Instead it reads
PT4M OR PT53S
Is there a way to edit the formula to address each variant that potential could occur?
Where it would format PT4M into 4:00 or PT53S into 0:53
Lastly, if the seconds in the duration are between 1-9 the API returns a single digit value for the seconds. Which means the formula above will look wrong. For example, PT1M1S is formatted into 1:1 when it should read 1:01
It would be great if the formula could account for the first 9 seconds and add a 0 to make it more readable.
Thanks for reading this far, if anyone could help me out I'd very much appreciate it.
Just in case its easier to do this within the script itself here's the custom script that retrieves the video duration.
function getYoutubeTime(videoId){
var url = "https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=" + videoId;
url = url + "&key=";
var videoListResponse = UrlFetchApp.fetch(url);
var json = JSON.parse(videoListResponse.getContentText());
return json["items"][0]["contentDetails"]["duration"];
}
Is very ugly, but seems to work for the examples provided:
=iferror(left(mid(A1,3,len(A1)-2),find("M",mid(A1,3,len(A1)-2))-1)*60,0)+substitute(REGEXreplace(mid(A1,3,len(A1)-2),"(.+M)",""),"S","")
Outputs seconds, eg 203 from PT3M23S. To change to 00:03:23 wap the above formula in ( ... )/86400 and format result as Time.
Script Solution:
function iso8601HMparse(str) {
return str.replace(/PT(\d+(?=M))?M?(\d+(?=S))?S?/g,function(mm,p1,p2){//regex to get M and S value
return [0,p1,p2].map(function(e){
e = e ? e:0;
return ("00"+e).substr(-2); //fix them to 2 chars
}).join(':');
})
}
Splice it in your script like:
return iso8601HMparse(json["items"][0]["contentDetails"]["duration"].toString());
Spreadsheet Function:
=TEXT(1*REGEXREPLACE(REGEXREPLACE(A1,"PT(\d+M)?(\d+?S)?","00:00$1:00$2"),"[MS]",),"MM:SS")
Late to the party, but here's what I'm using:
=TIMEVALUE(
IFERROR(TEXT(MID(A1,3,FIND("H",A1)-3),"00"),"00")&":"&
IFERROR(TEXT(MID(A1,IFERROR(FIND("H",A1)+1,3),FIND("M",A1)-IFERROR(FIND("H",A1)+1,3)),"00"),"00")&":"&
IFERROR(TEXT(MID(A1,IFERROR(FIND("M",A1)+1,3),FIND("S",A1)-IFERROR(FIND("M",A1)+1,3)),"00"),"00"))
You can also stick ARRAYFORMULA in front of this and change A1 to a a column to get values for a whole list of them.

Split a string using regex or other optimized way

I have a very simple string of the form
YYYYMMDDHHMMSS
Basically a full date/time string. Say an example is
20170224134523
Above implies
year: 2017
month: 02
day:24
hour:13
min:45
sec:23
I want to split it so that i can have it in variables (year, month, day, hour, min, sec). This is in Scala I want to. I was thinking should I use a 6-Tuple and on the right side I will use a regex or what as the most efficient way. If I want to do it in a concise way is what I am trying to think. Little bad with regular expressions.
Can anyone help?
I may want to have each variable in the 6-tuple as option type because otherwise that will also do my sanity check? Say if any variable comes out as None, I want to throw an exception
java.text.SimpleDateFormat handles this kind of date parsing well.
scala> val sdf = new SimpleDateFormat("yyyyMMddkkmmss")
sdf: java.text.SimpleDateFormat = java.text.SimpleDateFormat#8e10adc0
scala> val date = sdf.parse("20170224134523")
date: java.util.Date = Fri Feb 24 13:45:23 PST 2017
You can get the date, day, hours, etc from a successful parse of the date as the API shows below.
scala> res0.get
getClass getDate getDay getHours getMinutes getMonth getSeconds getTime getTimezoneOffset getYear
Further, I'd suggest wrapping the parse call in a Try to handle the successful and unsuccessful parsing.
scala> val date = Try(sdf.parse("20170224134523"))
date: scala.util.Try[java.util.Date] = Success(Fri Feb 24 13:45:23 PST 2017)
scala> val date = Try(sdf.parse("asdf"))
date: scala.util.Try[java.util.Date] = Failure(java.text.ParseException: Unparseable date: "asdf")
Here's the same thing using the newer LocalDateTime instead of Date and it's deprecated methods.
LocalDateTime.parse("20170224134523", DateTimeFormatter.ofPattern("yMMddkkmmss"))
java.time.LocalDateTime = 2017-02-24T13:45:23
Because it is a date string it probably makes sense to use a dedicated date parsing library and parse to a datetime type. Fortunatly, java provides a very good one with the java.time package.
val dateTime = LocalDateTime.parse("20170224134523", DateTimeFormatter.ofPattern("yyyyMMddHHmmss"))
Which will produce a LocalDateTime object (date and time without a timezone attached). If you need more complicated string parsing you can use a DateTimeFormatterBuilder to customize the date format exactly as you need it.
With such a predictable format you can grab it by position using a substring function (from, to) into a date class.
The regex pattern to grab the sections as groups is:
(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})
Demo

How to format this date as a string

Here is my scenario. I am getting this date from a database:
11-AUG-15 10.38.00.000000000 AM
Is there any way to format this string to look something similar to mm/dd/yy?
So far I have tried the following with no luck:
DateFormat()
CreateODBCDate()
LSParseDateTime()
Every time I use one of the above, I get the following error:
11-AUG-15 10.38.00.000000000 AM is an invalid date or time string.
Any advise will be greatly appreciated.
Thanks!
parseDateTime("11-AUG-15 10.38.00.000000000 AM", "dd-MMM-yy hh.mm.ss.S aa");
Run me: http://trycf.com/gist/aac6d63777ae1b0e9aa3/acf?theme=monokai
Then you are free to use DateFormat() or DateTimeFormat()to format the date object.

C++ boost date format

I have a vector string of dates in the from "dd-mmm-yyyy" so for example
todays date would be:
std::string today("07-Sep-2010");
I'd like to use the date class in boost but to create a date object the
constructor for date needs to be called as follows:
date test(2010,Sep,07);
Is there any easy/elegant way of passing dates in the format "dd-mmm-yyyy"?
My first thought was to use substr and then cast it? But I've read that there's also
the possibility of using 'date facets'?
Thanks!
include "boost/date_time/gregorian/parsers.hpp"
date test = boost::gregorian::from_us_string("07-Sep-2010")
There is a builtin parser for this form of date in Boost itself, check out the docs here:
http://www.boost.org/doc/libs/1_44_0/doc/html/date_time/date_time_io.html#date_time.io_objects
date_type parse_date(...)
Parameters:
string_type input
string_type format
special_values_parser
Parse a date from the given input using the given format.
string inp("2005-Apr-15");
string format("%Y-%b-%d");
date d;
d = parser.parse_date(inp,
format,
svp);
// d == 2005-Apr-15
with inp adjusted for your needs.