How to convert string to hours in dart? - dart

I have string like "080000000000" mean 08.00 AM. So, i'm using format DateFormat('jm');
I tried to substring 4 first string convert using DateTime.parse but throws an exception.
How to achieve the given string to 08.00 AM?

As you are only Dealing with
Time of the Day
You can use - TimeOfDay class
Code :
String myVal = "080000000000";
String myHour = myVal.substring(0, 2);
String myMin = myVal.substring(2, 4);
TimeOfDay releaseTime = TimeOfDay(hour: int.parse(myHour), minute: int.parse(myMin));
print(releaseTime.format(context)); // 8:00 AM
Also for accepted string for
DateTime parse (
String formattedString
)
you can check Examples of accepted strings: - https://api.dartlang.org/stable/2.2.0/dart-core/DateTime/parse.html
For 24-hours format - add:
MaterialApp(
builder: (context, child) =>
MediaQuery(data: MediaQuery.of(context).copyWith(alwaysUse24HourFormat: true), child: child),

Related

Flutter/Dart DateTime parsing UTC and converting to local

I am trying to parse a UTC Date string to DateTime and then parse it to local, however I am having troubles with converting it to the local time. In the UK it should be plus one, however when I print .isUtc it returns as false.
This is what I have now:
print(widget.asset.purchaseDate);
DateTime temp = DateTime.parse(widget.asset.purchaseDate);
print(temp.toLocal());
I/flutter (5434): 2020-05-07 21:29:00
I/flutter (5434): 2020-05-07 21:29:00.000
You need to indicate a timezone to DateTime.parse, otherwise it assumes local time. From the dartdoc:
An optional time-zone offset part, possibly separated from the
previous by a space. The time zone is either 'z' or 'Z', or it is a
signed two digit hour part and an optional two digit minute part.
Since you know your string represents UTC, you can tell the parser by adding the Z suffix.
var temp = DateTime.parse(widget.asset.purchaseDate + 'Z');
print(temp.isUtc); // prints true
While #Richard Heap's answer stands I'd like DateTime.parseUtc() to exist.
If there will be a day when dart allows static extension methods here is an implementation that would work:
extension DateTimeExtension on DateTime {
static DateTime parseUtc(String formattedDate) => DateTime.parse('${formattedDate}z');
static DateTime? tryParseUtc(String? formattedDate) {
if (formattedDate != null) {
return DateTime.tryParse('${formattedDate}z');
}
return null;
}
}
Currently you'd have to use it with the extension classes name, like so:
DateTimeExtension.parseUtc(someDate)
or
DateTimeExtension.tryParseUtc(someOtherDate)
I think the latter is more useful where someOtherDate is nullable

How to give a date Format to the sting parameter in query string? [duplicate]

I have to convert string in mm/dd/yyyy format to datetime variable but it should remain in mm/dd/yyyy format.
string strDate = DateTime.Now.ToString("MM/dd/yyyy");
Please help.
You are looking for the DateTime.Parse() method (MSDN Article)
So you can do:
var dateTime = DateTime.Parse("01/01/2001");
Which will give you a DateTime typed object.
If you need to specify which date format you want to use, you would use DateTime.ParseExact (MSDN Article)
Which you would use in a situation like this (Where you are using a British style date format):
string[] formats= { "dd/MM/yyyy" }
var dateTime = DateTime.ParseExact("01/01/2001", formats, new CultureInfo("en-US"), DateTimeStyles.None);
You need an uppercase M for the month part.
string strDate = DateTime.Now.ToString("MM/dd/yyyy");
Lowercase m is for outputting (and parsing) a minute (such as h:mm).
e.g. a full date time string might look like this:
string strDate = DateTime.Now.ToString("MM/dd/yyyy h:mm");
Notice the uppercase/lowercase mM difference.
Also if you will always deal with the same datetime format string, you can make it easier by writing them as C# extension methods.
public static class DateTimeMyFormatExtensions
{
public static string ToMyFormatString(this DateTime dt)
{
return dt.ToString("MM/dd/yyyy");
}
}
public static class StringMyDateTimeFormatExtension
{
public static DateTime ParseMyFormatDateTime(this string s)
{
var culture = System.Globalization.CultureInfo.CurrentCulture;
return DateTime.ParseExact(s, "MM/dd/yyyy", culture);
}
}
EXAMPLE: Translating between DateTime/string
DateTime now = DateTime.Now;
string strNow = now.ToMyFormatString();
DateTime nowAgain = strNow.ParseMyFormatDateTime();
Note that there is NO way to store a custom DateTime format information to use as default as in .NET most string formatting depends on the currently set culture, i.e.
System.Globalization.CultureInfo.CurrentCulture.
The only easy way you can do is to roll a custom extension method.
Also, the other easy way would be to use a different "container" or "wrapper" class for your DateTime, i.e. some special class with explicit operator defined that automatically translates to and from DateTime/string. But that is dangerous territory.
Solution
DateTime.Now.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture)
I did like this
var datetoEnter= DateTime.ParseExact(createdDate, "dd/mm/yyyy", CultureInfo.InvariantCulture);
You can change the format too by doing this
string fecha = DateTime.Now.ToString(format:"dd-MM-yyyy");
// this change the "/" for the "-"
The following works for me.
string strToday = DateTime.Today.ToString("MM/dd/yyyy");

unable to convert string date in Format yyyyMMddHHmmss to DateTime dart

i have a string containing date in format yyyyMMddHHmmss (e.g.) (20180626170555) and i am using following code to convert it into date time
dateTimeFromString(json['dateTime'], "yyyyMMddHHmmss")
exception is:
FormatException: Trying to read MM from 20180623130424 at position 14
what can be the reason?
DateTime.parse("string date here") accept some formatted string only. Check below examples of accepted strings.
"2012-02-27 13:27:00"
"2012-02-27 13:27:00.123456789z"
"2012-02-27 13:27:00,123456789z"
"20120227 13:27:00"
"20120227T132700"
"20120227"
"+20120227"
"2012-02-27T14Z"
"2012-02-27T14+00:00"
"-123450101 00:00:00 Z": in the year -12345.
"2002-02-27T14:00:00-0500": Same as "2002-02-27T19:00:00Z"
=> String to DateTime
DateTime tempDate = new DateFormat("yyyy-MM-dd hh:mm:ss").parse(savedDateString);
=> DateTime to String
String date = DateFormat("yyyy-MM-dd hh:mm:ss").format(DateTime.now());
Reference links:
Use intl for DateFormat from flutter package (https://pub.dev/packages/intl)
DateTime.parse() => https://api.dart.dev/stable/2.7.2/dart-core/DateTime/parse.html
intl DateFormat can't cope with your input string as it doesn't have any separators. The whole string gets consumed as the year. However DateTime.parse does cope with this (nearly). It happens to expect precisely the format you have (again, nearly).
One of the acceptable styles to parse is 20120227T132700, which just differs by the T date/time separator.
Try this:
String date = '20180626170555';
String dateWithT = date.substring(0, 8) + 'T' + date.substring(8);
DateTime dateTime = DateTime.parse(dateWithT);
to convert from "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" to 'MM/dd/yyyy hh:mm a'
date = '2021-01-26T03:17:00.000000Z';
DateTime parseDate =
new DateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse(date);
var inputDate = DateTime.parse(parseDate.toString());
var outputFormat = DateFormat('MM/dd/yyyy hh:mm a');
var outputDate = outputFormat.format(inputDate);
print(outputDate)
output
01/26/2021 03:17 AM
You can use DateFormat to parse a DateTime from string to an object
// With en_US locale by default
var newDateTimeObj = new DateFormat().add_yMd().add_Hms().parse("7/10/1996 10:07:23")
// with a defined format
var newDateTimeObj2 = new DateFormat("dd/MM/yyyy HH:mm:ss").parse("10/02/2000 15:13:09")
Check the doc here.
The Easient way convert a string into Date format is
print(DateTime.parse('2020-01-02')); // 2020-01-02 00:00:00.000
print(DateTime.parse('20200102')); // 2020-01-02 00:00:00.000
print(DateTime.parse('-12345-03-04')); // -12345-03-04 00:00:00.000
print(DateTime.parse('2020-01-02 07')); // 2020-01-02 07:00:00.000
print(DateTime.parse('2020-01-02T07')); // 2020-01-02 07:00:00.000
print(DateTime.parse('2020-01-02T07:12')); // 2020-01-02 07:12:00.000
print(DateTime.parse('2020-01-02T07:12:50')); // 2020-01-02 07:12:50.000
print(DateTime.parse('2020-01-02T07:12:50Z')); // 2020-01-02 07:12:50.000Z
print(DateTime.parse('2020-01-02T07:12:50+07')); // 2020-01-02 00:12:50.000Z
print(DateTime.parse('2020-01-02T07:12:50+0700')); // 2020-01-02 00:12:50.00
print(DateTime.parse('2020-01-02T07:12:50+07:00')); // 2020-01-02 00:12:50.00
From the docs, you need Single M to month in year :
dateTimeFromString(json['dateTime'], "yMdHms")
Basic information about how to convert String to Date and Date to string in flutter. Look at below link
https://quickstartflutterdart.blogspot.com/2018/10/how-to-convert-string-to-date-and-date.html
Might be it will be helped for others.
i did something like this (using the intl package)
final date = '7/10/1996';
final month = DateFormat.LLLL().format(DateTime.parse(date));
LLLL in the code above is date format skeleton meaning 'stand alone month', other date formatter is presented here
add String date as a parameter
DateTime.prase(String userString);
If you have a date and time string in a specific format, you can convert it to a DateTime object by using the parse() method. For example, if you have a string that contains “12/03/2019 9:45 AM”, you can use the parse() method to convert it to a DateTime object like this:
var dateTimeString = “12/03/2019 9:45 AM”;
var dateTimeObject = DateTime.parse(dateTimeString);
print(dateTimeObject); // 12/03/2019 09:45:00.000
The parse() method is very versatile and can handle a variety of different formats. If your string doesn’t follow a strict format, you can use tryParse() instead. This method will return null if it fails to parse the string.
for detail click here
https://mycodingwork.com/flutter-convert-string-to-datetime/
String startdate1="10/31/2022";
String endate1="11/02/2022";
DateTime start = new DateFormat("MM/dd/yyyy").parse(startdate1);
DateTime end = new DateFormat("MM/dd/yyyy").parse(enddate1);
DateTime s = DateTime(start.year, start.month, start.day);
DateTime to = DateTime(end.year, end.month, end.day);
int day= (to.difference(s).inHours / 24).round()+1;

How do I arrange date time in following format

Hi I am working C# MVC project. I have got date like this
string datetime = frmcollection["txtTo"].ToString()
Here datetime variable contains date and time in following format : 06/05/2014 10:25:39
Now I need to above datetime in int, so i replaced all /, :, and space.
So now i have following result :
int datetime = 0;
datetime = intdatetime
so here datetime variable has following reuslts : 6052014102539
So what I need here is, I need to store int time in different format like this : 2014060514102539. so basically i need to rearrange position of inttime.
How can i do this ??
string datetime = frmcollection["txtTo"].ToString();
// your date format that is coming from form collection...
string yourDateFormat = "MM-dd-yyyy HH:mm:ss";
// convert string to date time
DateTime newDate = DateTime.ParseExact(datetime, yourDateFormat, null);
// change its format and convert it to string
string newDateStr = newDate.ToString("yyyy/MM/dd HH:mm:ss");
and use your "string to int" method...
Create a method that takes your string, parses it to a date and returns a weird datetime int. Something like this:
public int ParseDateToWeirdInt(string date)
{
//Error checking omitted
var d = DateTime.Parse(date);
var stringThatWillBecomeAnInt = "";
stringThatWillBecomeAnInt = d.Year.ToString();
stringThatWillBecomeAnInt += d.Month.ToString();
stringThatWillBecomeAnInt += d.Date.ToString();
stringThatWillBecomeAnInt += d.TimeOfDay.Hours.ToString();
stringThatWillBecomeAnInt += d.TimeOfDay.Minutes.ToString();
stringThatWillBecomeAnInt += d.TimeOfDay.Seconds.ToString();
return int.Parse(stringThatWillBecomeAnInt);
}
You should probably use a StringBuilder instead of concatenating the string and a recommendation would be to turn the method into an extension method. Also note that the method needs much better error handling (the date parse could fail, the int parse could fail etc.).
Thanks guys for helping me out. I found this solution as easy for me .
datetime = Convert.ToDateTime(datetime ).ToString("yyyy/dd/MM HH:mm:ss");
so now i have datetime in format i need. Now i can convert to int.
Just adding this answer as a cleaner solution
string datetime = frmcollection["txtTo"].ToString();
string newDateTime;
DateTime theDateTime;
if (DateTime.TryParse(datetime, out theDateTime))
{
newDateTime = theDateTime.ToString("yyyy/dd/MM HH:mm:ss");
}
else
{
// tell user they have entered the date in wrong format
}

Parse finnish date string to Date Type in VB6

I'm getting a Finnish date string that looks like:
29.7.2011 9:27
I'm trying to cast this string to a Date object in VB6. I've tried using the Format function but it doesn't seem to swallow the date string or I'm doing something wrong. These are some approaches I've tried:
theDate = Format(dateString, "General Date")
theDate = Format(dateString, "DD.MM.YYYY MM:HH")
Any ideas? Thanks.
Rather than manually parsing the string yourself, which is prone to errors, and which gets messy if you have to deal with multiple date formats, you can call out to the OLE Automation library (which VB6 uses internally for many things, including type conversions) to do the conversion for you. It can convert strings in any date/time format supported by Windows back into a raw Date.
Full disclosure: I agree with the sentiment in Deanna's
answer: in general, you should try to use an unambiguous date/time
format when converting dates to and from strings, but if you cannot do
this for some reason, the solution outlined here should be fairly robust, as long as you know ahead of time what specific format the incoming date string will be in.
Below is an example of a DateFromString function that uses the VarDateFromStr function internally to convert a formatted date/time String into a Date.
Example Usage
Convert a Finnish date string to a Date and display it:
MsgBox DateFromString("29.7.2011 9:27", fl_FI)
On my machine (US English settings), this displays "7/29/2011 9:27 AM", which is the correct date and time (July 29).
Code
Place the code below into a new module (.bas file) in your project to use it. The code currently supports parsing US English (en_US) and Finnish (fl_FI) date strings, but you can add support for more locales if needed. See Locale IDs assigned by Microsoft for a complete list of locale ID's.
Option Explicit
Public Enum LocaleIDs
en_US = &H409 ' English (United States)
fl_FI = &H40B ' Finnish
' [[ Add other Locale ID's here as needed ]] '
End Enum
Private Declare Function VarDateFromStr Lib "oleaut32.dll" ( _
ByVal psDateIn As Long, _
ByVal lcid As Long, _
ByVal uwFlags As Long, _
ByRef dtOut As Date) As Long
Private Const S_OK = 0
Private Const DISP_E_BADVARTYPE = &H80020008
Private Const DISP_E_OVERFLOW = &H8002000A
Private Const DISP_E_TYPEMISMATCH = &H80020005
Private Const E_INVALIDARG = &H80070057
Private Const E_OUTOFMEMORY = &H8007000E
'
' Converts a date string in the specified locale to a VB6 Date.
'
' Example:
'
' Convert a Finnish date string as follows:
'
' DateFromString("29.7.2011 9:27", fl_FI)
'
Public Function DateFromString(ByVal sDateIn As String, ByVal lcid As LocaleIDs) As Date
Dim hResult As Long
Dim dtOut As Date
' Do not want user's own settings to override the standard formatting settings
' if they are using the same locale that we are converting from.
'
Const LOCALE_NOUSEROVERRIDE = &H80000000
' Do the conversion
hResult = VarDateFromStr(StrPtr(sDateIn), lcid, LOCALE_NOUSEROVERRIDE, dtOut)
' Check return value to catch any errors.
'
' Can change the code below to return standard VB6 error codes instead
' (i.e. DISP_E_TYPEMISMATCH = "Type Mismatch" = error code 13)
'
Select Case hResult
Case S_OK:
DateFromString = dtOut
Case DISP_E_BADVARTYPE:
Err.Raise 5, , "DateFromString: DISP_E_BADVARTYPE"
Case DISP_E_OVERFLOW:
Err.Raise 5, , "DateFromString: DISP_E_OVERFLOW"
Case DISP_E_TYPEMISMATCH:
Err.Raise 5, , "DateFromString: DISP_E_TYPEMISMATCH"
Case E_INVALIDARG:
Err.Raise 5, , "DateFromString: E_INVALIDARG"
Case E_OUTOFMEMORY:
Err.Raise 5, , "DateFromString: E_OUTOFMEMORY"
Case Else
Err.Raise 5, , "DateFromString: Unknown error code returned from VarDateFromStr (0x" & Hex(hResult) & ")"
End Select
End Function
You can use DateSerial and 'TimeSerial' in the following way
dateString = "29.7.2011 9:27"
Dim theDate as Date
dim yyyy as Integer
dim mm as Integer
dim dd as Integer
dim hh as integer
dim mm as integer
yyyy = mid(dateString,6,4)
mm = mid(dateString,4,1)
dd = mid(dateString,1,2)
hh = mid(dateString,11,1)
mm = mid(dateString,13,2)
theDate = DateSerial(yyyy,mm,dd) + TimeSerial(hh,mm,0)
now you theDate is a Date object and can be formatted the way you want
MsgBox Format(theDate,"yyyy-MMM-dd") 'This will display the a message with 2011-Jul-29
If your date string is not padded with zeros (for example: 2.4.2011 instead of 02.04.2011) then you will need to loop through the string to find the bits and parts of the date that you will be needing.
Finnish systems should be able to parse these correctly using CDate(). If you're parsing it on a non finnish system and the format is fixed, then you will need to split it up in code:
Dim Parts() as string, dateParts() As String, timeParts() as string
parts = Split(dateString, " ")
dateParts = Split(parts(0), ".")
timeParts = Split(parts(1), ":")
theDate = DateSerial(dateParts(2), dateParts(1), dateParts(0)) + TimeSerial(timeParts(0), timeParts(1), 0)
You will probbaly want to add error handling and sanity checking to that but that is the basic idea.
Note that converting dates to and from string values will be error prone unless using very explicit unambigious agreed formats like ISO 8601, RFC 822 dates, and the iCal RFC 2445 standard.
Parsing is messy at best but here is a shorter sample how to do it
Private Sub Command1_Click()
MsgBox Format$(TryParse("29.7.2011 9:27"), "yyyymmdd hh:mm:ss")
End Sub
Private Function TryParse(sFinnishDate As String) As Date
Dim vSplit As Variant
vSplit = Split(Replace(Replace(sFinnishDate, ".", " "), ":", " "))
On Error Resume Next
TryParse = DateSerial(vSplit(2), vSplit(1), vSplit(0)) + TimeSerial(vSplit(3), vSplit(4), 0)
On Error GoTo 0
End Function

Resources