Parsing 24 HR Time to DateTime - flutter

I am attempting to convert the following 2HR time in String to a DateTime, so that I manage it appropriately.
"1800"
This question came close, but no one answered how to convert the String into a valid DateTime.
How to convert time stamp string from 24 hr format to 12 hr format in dart?
Attempt 1:
DateTime.parse("1800") -
Invalid Date Format
Attempt 2:
DateTime.ParseExact("1800") -
This doesn't seem to exist, although it shows up on various
Still no luck and need a second pair of eyes to point out the obvious to me.

The time by itself is not a datetime so you could do something like:
DateTime myTime(DateTime baseDate, String hhmm) {
assert(hhmm.length == 4, 'invalid time');
final _hours = int.parse(hhmm.substring(0, 2));
final _mins = int.parse(hhmm.substring(2, 2));
return DateTime(baseDate.year, baseDate.month, baseDate.day, _hours, _mins);
}

DateTime.parse expects to parse dates with times, not just times. (You can't even create a DateTime object without a date!)
Some people generate a dummy date string, but in your case you could trivially parse it with int.parse and then apply appropriate division and remainder operations:
var rawTime = int.parse('1800');
var hour = rawTime ~/ 100;
var minute = rawTime % 100;
Also see How do I convert a date/time string to a DateTime object in Dart? for more general DateTime parsing.

Related

Weird part of DateTime.parse(data['datetime']) in Dart

Problem Description
I have 020-03-20T14:16:27.189282+08:00 return from my database and I am trying to convert it to 2:16pm using DateTime.parse(). However,every time I convert the time, I get 6:16am.
Question
May I know how could I solve this problem?
MyCode
dateTime = `020-03-20T14:16:27.189282+08:00`
time = DateFormat.jm().format(DateTime.parse(dateTime));
print(time);
Dai, thanks for your small tips.
Solutions for this question is remove the offset from the string.
Why
The result is always in either local time or UTC. If a time zone offset other than UTC is specified, the time is converted to the equivalent UTC time.
Read it here https://api.dart.dev/stable/2.7.1/dart-core/DateTime/parse.html.
Answered
String dateTime = `020-03-20T14:16:27.189282+08:00`;
int indexOfPlusMinusSymbol = dateTime .indexOf('+') >= 0
?dateTime .lastIndexOf('+')
: dateTime .lastIndexOf('-');
String time = DateFormat.jm().format(DateTime.parse(dateTime..substring(0, indexOfPlusMinusSymbol)));
print(time);

Converting time in SPSS from hhmm:ss to hh:mm:ss (TIME8)

After a data export I get a string variable with "2017/02/22 1320:35 +000 4".
Through:
compute #TS = char.index(Timestamp_1, " ").
string date (A10).
compute date = char.substr(Timestamp_1,1,#TS).
alter type date (A10 = SDATE10).
I manage to get the date in a separate variable.
The same:
string time (A8).
compute time = char.substr(Timestamp_2,#TS+1,7).
alter type time (A8 = TIME8).
doesn't work for the time because it is in the 'hhmm:ss' format. How do I change the string variable '1320:35' into a time variable '13:20:35'?
You can insert a ":" manually into the time string by using the concat function before you alter the type.
COMPUTE time = CONCAT(CHAR.SUBSTR(time,1,2),":",(CHAR.SUBSTR(time,3))).
Another approach would be to extract hours, minutes and seconds from Timestamp variable individually and to use these elements inside the TIME.HMS function:
COMPUTE #hh = NUMBER(CHAR.SUBSTR(Timestamp_1,TS+1,2),F2).
COMPUTE #mm = NUMBER(CHAR.SUBSTR(Timestamp_1,TS+3,2),F2).
COMPUTE #ss = NUMBER(CHAR.SUBSTR(Timestamp_1,TS+6,2),F2).
COMPUTE time = TIME.HMS(#hh,#mm,#ss).
EXECUTE.
FORMATS time (TIME8).
Statistics has a datetime format and, new in V24, an ISO 8601 timestamp format, YMDHMS. If the string is converted to a regular date/time value, then the XDATE.DATE and XDATE.TIME functions can be used to extract the pieces. The Date and Time wizard may accommodate the format you have (not sure about that +000 4 part at the end).

method for converting seconds from date to datetime

Is there a method in matlab to convert seconds from a known date to a standard date time format?
For example, if I have a vector of values shown as seconds from 1901/01/01, how would I convert them to a dateTime? In this case a value of 28125 would correspond to 1981/01/01. Is there an efficient method for doing this?
The numbers in your example do not make sense so it is not clear if your time is in seconds or days but since you asked for seconds I will use this.
What you want to achieve can be done using datenum function. This function returns the number of (fractional) days from 1/1/0000. So first you need to find your offset, e.g.:
offsetInDays = datenum(1901,1,1);
Next, you convert the date from seconds to days:
dateInDays = YourRequiredDateInSec * 3600 * 24;
Finally, you date is given by
RequiredDate = datestr(offsetInDays + dateInDays);

Converting Date in Extjs

I have a Date string of following format:
'31-OCT-2013'
How do I convert this into Date of following format using Extjs 4:
'08/31/2013'
I am using IE8.
If you have string "31-OCT-2013", you need to:
Convert it into date object
var myDate = Ext.Date.parse("31-OCT-2013", 'd-M-Y');
Format it to as you want
Ext.Date.format(myDate, 'm/d/Y');
Try something like this:
If your day representation would be 2 digit with leading zero, then apply this
var date = Ext.Date.parse("31-OCT-2013", 'd-M-Y');
console.log(Ext.Date.format(date, 'm/d/Y'));
But if your day representation would be without a leading zero, then apply this
var date = Ext.Date.parse("31-OCT-2013", 'j-M-Y');
console.log(Ext.Date.format(date, 'm/d/Y'));
Check the docs for Ext.Date

What is the most efficient way to convert an eight digit number to a date?

I am using ColdFusion 9.0.1 and some database that I cannot change.
I am accessing a database that stores a date as an eight digit numeric with zero decimal places like this:
YYYYMMDD
I need to be able to read the date, add and subtract days from a date, and create new dates. I am looking for a ColdFusion solution to efficiently (not much code) to convert the date to our standard format, which is
MM/DD/YYYY
And then convert it back into the database's format for saving.
I need to code this in such a way that non-ColdFusion programmers can easily read this and use it, copy and modify it for other functions (such as adding a day to a date). So, I am not looking for the most least amount of code, but efficient and readable code.
Can you suggest anything that would make this code block more flexible, readable, or more efficient (less code)?
<cfscript>
// FORMAT DB DATE FOR BROWSER
DateFromDB = "20111116";
DatedToBrowser = createBrowserDate(DateFromDB);
writeOutput(DatedToBrowser);
function createBrowserDate(ThisDate) {
ThisYear = left(ThisDate, 4);
ThisMonth = mid(ThisDate, 4, 2);
ThisDay = right(ThisDate, 2);
NewDate = createDate(ThisYear, ThisMonth, ThisDay);
NewDate = dateFormat(NewDate, "MM/DD/YYYY");
return NewDate;
}
// FORMAT BROWSER DATE FOR DB
DateFromBrowser = "11/16/2011";
DateToDB = createDBDate(DateFromBrowser);
writeDump(DateToDB);
function createDBDate(ThisDate) {
ThisYear = year(ThisDate);
ThisMonth = month(ThisDate);
ThisDay = day(ThisDate);
NewDate = "#ThisYear##ThisMonth##ThisDay#";
return NewDate;
}
</cfscript>
First find who ever did the database and kick them in the nads...
Personally I'd Convert with sql so my code only dealt with date objects.
Select Convert(DateTime, Convert(VarChar(8),DateTimeInventedByIdjitColumn))
From SomeTable
As stated by our peers, store dates as dates.
'08/06/2011' could be 8th of june of the 6th of August depending on locale.
20111643 is a valid integer..
Not using a proper date type is just a massive collection of features and bugs that at best are waiting to happen.
You can actually rewrite each function into 1 line of code.
function createBrowserDate(ThisDate) {
return mid(ThisDate,4,2) & "/" & right(ThisDate,2) & "/" & left(ThisDate,4);
}
and
function createDBDate(ThisDate) {
return dateFormat( ThisDate, "YYYYMMDD" );
}
Don't keep dates as strings - keep dates as dates and format them when you need to.
If you can't correct the database to use actual date columns (which you should if you can), then you can use these two functions to convert to/from YYYYMMDD and a date object:
function parseYMD( YYYYMMDD )
{
if ( ! refind('^\d{8}$' , Arguments.YYYYMMDD ) )
throw "Invalid Format. Expected YYYYMMDD";
return parseDateTime
( Arguments.YYYYMMDD.replaceAll('(?<=^\d{4})|(?=\d{2}$)','-') );
}
function formatYMD( DateObj )
{
return DateFormat( DateObj , 'yyyymmdd' );
}
By using date objects it means that any level of developer can work with them, without needing to care about formatting, via built-in functions like DateAdd, DateCompare, and so on.
I'm not a regular expression fan since it's not that readable to me.
Since you're using CF9, I'd typed the argument and specify the returntype of the functions to be even more readable for the next person picking up your code.
First, right after I read the date from DB, I'd parse it to a Date object using parseDBDate()
Date function parseDBDate(required String dbDate)
{
var yyyy = left(dbDate, 4);
var mm = mid(dbDate, 4, 2);
var dd = right(dbDate, 2);
return createDate(yyyy , mm, dd);
}
Once you have the date object, you can use all those built-in Date functoin like DateAdd() or DateDiff().
Call browserDateFormat() right before you need to display it.
String function browserDateFormat(required Date date)
{
return dateFormat(date, "MM/DD/YYYY");
}
Call dBDateFormat() inside <cfqueryparam value=""> when it's time to persist to DB
String function dBDateFormat(required Date date)
{
return dateFormat(date, "YYYYMMDD");
}
One liner :)
myDateString = "20110203";
myCfDate = createObject("java","java.text.SimpleDateFormat").init("yyyyMMdd").parse(myDateString,createObject("java","java.text.ParsePosition").init(0*0));
If you want to parse different patterns, change "yyyyMMdd" to any other supported pattern.
http://download.oracle.com/javase/1.5.0/docs/api/java/text/SimpleDateFormat.html
The ParsePosition is used to say where to start parsing the string.
0*0 is shorthand for JavaCast("int",0) - in the Adobe cf engine, 0 is a string, until you apply math to it, then it becomes a Double, which the ParsePosition constructor supports. Technically, it constructs with an int, but cf is smart enough to downgrade a Double to an int.
http://download.oracle.com/javase/1.5.0/docs/api/java/text/ParsePosition.html