Split a string using regex or other optimized way - regex

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

Related

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

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

Age checker 18+ with regular expressions

Can you help me please to do age checker with regular expression? I don't know how to calculate if user is 18 or not.
Input: user's birthday (in format of REGEX)
Output: "welcome" or "come back when you will be 18+"
Here is my code for checking if format is ok and bad:
import re
import datetime
pattern = re.compile("^(0[1-9]|[12][0-9]|3[01])[- \/.,_](0[1-9]|1[012])[- \/.,_](19|20)\d\d")
dob = input('Enter your birthday (dd/mm/yyyy): ')
result = pattern.match(dob)
if pattern.match(dob):
print("format is ok")
else:
print("format is bad")
Thank you in advance!!!
Instead of using regex just try to use the input to create a datetime object - if it works the format is good else input is invalid (see datetime.strptime(date_string, format)).
Once you have it and you have datetime.now() you can easily calculate the age
Okay, so you have the requirement to do it with a regular expression.
Be aware, that this could lead to some edge cases not being covered!
import re
import datetime
pattern = re.compile("^(0[1-9]|[12][0-9]|3[01])[- \/.,_](0[1-9]|1[012])[- \/.,_](19|20)\d\d")
dob = input('Enter your birthday (dd/mm/yyyy): ')
result = pattern.match(dob)
if pattern.match(dob):
print("format is ok")
else:
print("format is bad")
Okay, the regular expression seem to be valid (except the capturing group for the year. You could use Regexr or similiar services if you need to refine it).
Then you can deconstruct the matched groups to get the day, month and year:
[day, month, year] = result.groups() # As mentioned, year is currently either 19 or 20
Then, the next step would be to compare the month against the current month. This will help decide on whether to add a year or not. In case it happens to be the same or an adjacent month, you might want to look at the days, too.
Finally, subtract the current year from the entered one (once you fixed the year capturing group) and do the math.
Since it's an assignment, I won't provide the code for this ;-)

PARSE_DATETIME formatting with day of year

Having an issue with the PARSE_DATETIME function in BigQuery used with the day of year (%j) formatting element. The function seems to ignore the day of year element.
Eg.
select PARSE_DATETIME("%Y%j", "2013243")
returns 2013-01-01T00:00:00, lacking day of year component.
However the reverse function with the same date formatting elements works as expected:
select FORMAT_DATETIME("%Y%j", "2013-02-02T00:00:00")
returns: 2013033
Bug? or user error?
Cheers
I think that this is a bug that could be fixed! there is no logic in it working one way but not opposite!
Meantime, you can use below to achieve goal
#standardSQL
CREATE TEMP FUNCTION PARSE_DATETIME_WITH_DAYS(x STRING) AS (
DATETIME_ADD(PARSE_DATETIME('%Y%j', x), INTERVAL CAST(SUBSTR(x, -3) AS INT64) - 1 DAY)
);
SELECT PARSE_DATETIME_WITH_DAYS('2013243')
with result -
Row f0_
1 2013-08-31T00:00:00
Not a bug, neither an error! PARSE_DATETIME uses a format_string and a STRING representation of a DATETIME to return a DATETIME -> "2013243" does not represent a DATETIME string, not a DATE...
To achieve what you are looking for first get the day number - 1 and add it to date (first day of the year) and format the output to DATETIME
SELECT DATETIME(DATE_ADD((SELECT PARSE_DATE("%Y%j", "2013243")), INTERVAL CAST((SELECT SUBSTR("2013243", -3)) AS INT64) -1 DAY));
Output:
2013-08-31T00:00:00

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.