How to format DateTime to local users locale in short time format using MonoTouch - datetime

I've tried multiple approaches, this is one of them:
System.Globalization.DateTimeFormatInfo format = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat;
return dt.Value.ToString (format.ShortTimePattern);
The problem with this one is that .NET 3.5 returns a "." as the time seperator which is most likely a bug (since my Norwegian locale uses a colon):
.NET (3.5) formats times using dots instead of colons as TimeSeparator for it-IT culture?
I also looked here:
Retrieving current local time on iPhone?
But MT doesn't seem to have setTimeStyle on the NSDateFormatter?
So, anyone have any magic tricks up their sleeves?
My goal is to output:
21:00 / 9:00 PM
10:09 / 10:09 AM
like the statusbar in iPhone.

Try this:
var formatter = new NSDateFormatter ();
formatter.TimeStyle = NSDateFormatterStyle.Short;
Console.WriteLine (formatter.ToString (DateTime.Now));
That said, the bug with dot/colon as the time separator for Norwegian locales has been fixed in Mono 2.12, so when MonoTouch switches to use Mono 2.12 instead of Mono 2.10 (hopefully early next year) you will be able to use this managed alternative too:
Console.WriteLine (DateTime.Now.ToString (new CultureInfo ("nb-NO").DateTimeFormat.ShortTimePattern));

I made a small research on mono sources and found that ShortTimePattern and TimeSeperator are not relate on each other (please Mono-guru's correct me if I'm wrong).
So, I tried to make iOS-only (not cross-platform) solution. That is is:
using MonoTouch.Foundation;
...
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
var d = DateTime.Now;
Console.WriteLine("NSDate: " + GetCorrectTime(d));
}
...
// iOS-only (not cross-platform)
public string GetCorrectTime (DateTime d)
{
var nsdate = DateTimeToNSDate(d);
var nsdateformatter = new .NSDateFormatter();
nsdateformatter.DateStyle = NSDateFormatterStyle.None;
nsdateformatter.TimeStyle = NSDateFormatterStyle.Short;
return nsdateformatter.ToString(nsdate);
}
...
// DateTime to NSDate was taken from [that post][2]
public static NSDate DateTimeToNSDate(DateTime date)
{
return NSDate.FromTimeIntervalSinceReferenceDate((date-(new DateTime(2001,1,1,0,0,0))).TotalSeconds);
}
Output:
NSDate: 17:40
Please note that I'd test it with simulator and "nn-NO" (Norwegian Nynorsk (Norway)) locale.

Related

Convert datetime to other runtimetype in flutter app

I'm trying to convert a DateTime runtimetype value to Expression<DateTime, DateTimeType>. I've been trying to achieve this for almost three days now. I have tried different approaches but non is working.
The reason I want to achieve this is because moor_flutter library in some cases uses and accepts the library's custom runtimetypes on methods and and the parameter values on those methods.
Below is the sample code;
final DateTime dateToday = new DateTime.now(); // convert DateTime to Expression<DateTime, DateTimeType>
var dateWithNewRuntimetype; // assign the converted value to this variable
I thought I fixed this issue by adding as as Expression<DateTime, DateTimeType> to the value of dateWithNewRuntimetype variable value but no this is not the solution either.
The solution will work on the code below
Stream<List> getLoansWithTomorrowDueDate(int dayInFuture) {
return (select(loans)
..where((l) => l.due_date.isBetween(
dateToday, // it should be Expression<DateTime, DateTimeType> not DateTIme
futureDate, // it should be Expression<DateTime, DateTimeType> not DateTIme)))
.watch();
}
If you want me to provide more info on this I will do so.
Thank you, so much Love.
The isBetween is compared withSqlType.
You must use isBetweenValues.
/// Defines extension functions to express comparisons in sql
extension ComparableExpr<DT, ST extends ComparableType<DT>>
on Expression<DT, ST> {
Expression<bool, BoolType> isBetween(
Expression<DT, ST> lower, Expression<DT, ST> higher,
{bool not = false});
Expression<bool, BoolType> isBetweenValues(DT lower, DT higher,
{bool not = false});
}

How do I convert a date/time string to a DateTime object in Dart?

Say I have a string
"1974-03-20 00:00:00.000"
It is created using DateTime.now(),
how do I convert the string back to a DateTime object?
DateTime has a parse method
var parsedDate = DateTime.parse('1974-03-20 00:00:00.000');
https://api.dartlang.org/stable/dart-core/DateTime/parse.html
There seem to be a lot of questions about parsing timestamp strings into DateTime. I will try to give a more general answer so that future questions can be directed here.
Your timestamp is in an ISO format. Examples: 1999-04-23, 1999-04-23 13:45:56Z, 19990423T134556.789. In this case, you can use DateTime.parse or DateTime.tryParse. (See the DateTime.parse documentation for the precise set of allowed inputs.)
Your timestamp is in a standard HTTP format. Examples: Fri, 23 Apr 1999 13:45:56 GMT, Friday, 23-Apr-99 13:45:56 GMT, Fri Apr 23 13:45:56 1999. In this case, you can use dart:io's HttpDate.parse function.
Your timestamp is in some local format. Examples: 23/4/1999, 4/23/99, April 23, 1999. You can use package:intl's DateFormat class and provide a pattern specifying how to parse the string:
import 'package:intl/intl.dart';
...
var dmyString = '23/4/1999';
var dateTime1 = DateFormat('d/M/y').parse(dmyString);
var mdyString = '04/23/99';
var dateTime2 = DateFormat('MM/dd/yy').parse(mdyString);
var mdyFullString = 'April 23, 1999';
var dateTime3 = DateFormat('MMMM d, y', 'en_US').parse(mdyFullString));
See the DateFormat documentation for more information about the pattern syntax.
DateFormat limitations:
DateFormat cannot parse dates that lack explicit field separators. For such cases, you can resort to using regular expressions (see below).
Prior to version 0.17.0 of package:intl, yy did not follow the -80/+20 rule that the documentation describes for inferring the century, so if you use a 2-digit year, you might need to adjust the century afterward.
As of writing, DateFormat does not support time zones. If you need to deal with time zones, you will need to handle them separately.
Last resort: If your timestamps are in a fixed, known, numeric format, you always can use regular expressions to parse them manually:
var dmyString = '23/4/1999';
var re = RegExp(
r'^'
r'(?<day>[0-9]{1,2})'
r'/'
r'(?<month>[0-9]{1,2})'
r'/'
r'(?<year>[0-9]{4,})'
r'$',
);
var match = re.firstMatch(dmyString);
if (match == null) {
throw FormatException('Unrecognized date format');
}
var dateTime4 = DateTime(
int.parse(match.namedGroup('year')!),
int.parse(match.namedGroup('month')!),
int.parse(match.namedGroup('day')!),
);
See https://stackoverflow.com/a/63402975/ for another example.
(I mention using regular expressions for completeness. There are many more points for failure with this approach, so I do not recommend it unless there's no other choice. DateFormat usually should be sufficient.)
import 'package:intl/intl.dart';
DateTime brazilianDate = new DateFormat("dd/MM/yyyy").parse("11/11/2011");
you can just use : DateTime.parse("your date string");
for any extra formating, you can use "Intl" package.
void main() {
var dateValid = "30/08/2020";
print(convertDateTimePtBR(dateValid));
}
DateTime convertDateTimePtBR(String validade)
{
DateTime parsedDate = DateTime.parse('0001-11-30 00:00:00.000');
List<String> validadeSplit = validade.split('/');
if(validadeSplit.length > 1)
{
String day = validadeSplit[0].toString();
String month = validadeSplit[1].toString();
String year = validadeSplit[2].toString();
parsedDate = DateTime.parse('$year-$month-$day 00:00:00.000');
}
return parsedDate;
}
a string can be parsed to DateTime object using Dart default function DateTime.parse("string");
final parsedDate = DateTime.parse("1974-03-20 00:00:00.000");
Example on Dart Pad
String dateFormatter(date) {
date = date.split('-');
DateFormat dateFormat = DateFormat("yMMMd");
String format = dateFormat.format(DateTime(int.parse(date[0]), int.parse(date[1]), int.parse(date[2])));
return format;
}
I solved this by creating, on the C# server side, this attribute:
using Newtonsoft.Json.Converters;
public class DartDateTimeConverter : IsoDateTimeConverter
{
public DartDateTimeConverter()
{
DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFK";
}
}
and I use it like this:
[JsonConverter(converterType: typeof(DartDateTimeConverter))]
public DateTimeOffset CreatedOn { get; set; }
Internally, the precision is stored, but the Dart app consuming it gets an ISO8601 format with the right precision.
HTH

How to compare two dates with each other in Flex?

I have a standard ISO8601 date string:
2004-02-12T15:19:21+00:00
I want to know if this date is older than 10 minutes ago in Flex. So basically:
if ("2004-02-12T15:19:21+00:00" > current_time - 10mins) {
// do whatever
}
What would the syntax be in Flex? I'm basically stuck at trying to convert the string into a Flex Date Object without parsing it character by character.
If you don;t care about the timezone i.e. the date string is in the same timezone as where you are running the application then this should work.
var date:Date = DateFormatter.parseDateString("2004-02-12T15:19:21+00:00");
var now:Date = new Date();
var tenMinAgo:Number = now.time - 1000*60*10;
if (date.time < tenMinAgo) {
trace("More than 10 min ago");
}

How to convert string in format DD/MM/YYYY to date object in Flex

I am taking date input from user in text field, which is in format DD/MM/YYYY.
How to convert this string to date object in Flex.
Platform: Adobe Flash Builder 4.6
Since Flex SDK 4.10.0 you can use
DateFormatter.parseDateString(s, "DD/MM/YYYY");
Former versions of parseDateString didn't respect a format string, so it cannot parse dateString value formatted with non default en_US format
Use DateField's stringToDate method. DateFormatter also has a parseDateString function but for some reason it's set to protected.
public function convertStringToDate(s:String):Date
{
return DateField.stringToDate(s, "DD/MM/YYYY");
}
If you are not on the latest Apache SDK (I know we aren't because of third party components) you basically have to write your own conversion.
The built in DateFormatter has the static method, parseDateString, but you have no way of specifying the format of the string. It was a bit rubbish!
If you definitely have no localisation issues and are sure the date is ALWAYS in DD/MM/YYYY format you could use the following:
public function stringToDate(date:String):Date {
// Extract year, month and day from passed in date string
var year:int = IntFromSubString(date, 6, 4);
var month:int = IntFromSubString(date, 3, 2);
var day:int = IntFromSubString(date, 0, 2);
// Always remember Flex months start from 0 (Jan=0, Feb=1 etc.) so take 1 off the parsed month
return new Date(year, month-1, day);
}
private static function IntFromSubString(date:String, start:int, length:int):int {
return parseInt(date.substr(start, length)) as int;
}

DateTime from CFDirectory not being interpreted correctly by ColdFusion

We have Coldfusion installed on Windows Server 2003
A dump of CFDirectory on the undelivered mail returns the following:
But the problem is upon iterating this query, when I dump the date with:
#dateFormat(mailStubs.DateLastModified,'dd-mmm-yyyy')#
This is what I get:
11-Nov-2026
11-Nov-2027
11-Nov-2028
11-Nov-2029
11-Nov-2029
11-Nov-2029
11-Nov-1930
11-Nov-1930
11-Nov-1930
11-Nov-1930
11-Nov-1930
11-Nov-1930
11-Nov-1930
11-Nov-1930
So doing:
datediff("n", mailStubs.DateLastModified, now())
now() being 30th Nov 2011 lets say 2:00 PM gives me very weird results
This only happens on Windows server 2003 (Our production server), it worked fine on my local system (XP)
Any ideas?
I know this is a really old thread, but ... cfdirectory returns a localized date string (not date object). So you should be using the LS (locale sensitive) date functions to parse it. The reason is that the standard CF date functions (DateFormat, ParseDateTime, ...) always use U.S. date conventions. Since the U.S. convention is month first, you will get the wrong results if you pass in a "dd-mm-yyyyy" date string. (At least some of the time.)
<cfscript>
setLocale("en_GB");
WriteOutput( dateFormat(lsParseDateTime("26/11/11 2:42 PM"), "dd-mmm-yyyy") );
</cfscript>
Looks like your modified dates are coming out in a format that dateFormat() doesn't recognise.
Try using a java SimpleDateFormat to convert to a cf "{ts}" date.
You create a SimpleDateFormat + ParsePosition, then in your loop, call the sdf.parse() method and reset the position with pp.setIndex(0)
If you want this to only run on your windows 2003 server, check the server scope server.os.version
<cfscript>
// init the class with a pattern that matches your wacky date string
// do this before you start looping
var sdf = createObject('java','java.text.SimpleDateFormat').init('dd/MM/yy HH:mm a');
// init a parse position, so the above class knows it's position during parsing
var pp = createObject('java','java.text.ParsePosition').init(0);
// run your loop
for ( var i = 1; i lte query.recordCount; i++ ) {
// convert the string date into a cf {ts} date.
cfdate = sdf.parse( query.myColumn[i], pp );
// reset the position for the next .parse() call
pp.setIndex(0);
// now you can use dateDiff() with your cfdate
// if the parse fails, cfdate will be undefined, so check with an isNull()
}
</cfscript>
Simple demonstration of it working:
<cfscript>
var dirty = [
'26/11/11 2:42 PM',
'27/11/11 10:53 PM',
'29/11/11 12:08 AM'
];
var sdf = createObject('java','java.text.SimpleDateFormat').init('dd/MM/yy HH:mm a');
var pp = createObject('java','java.text.ParsePosition').init(0);
var clean = [];
for ( var i = 1; i lte arrayLen( dirty ); i++ ) {
clean[i] = sdf.parse( dirty[i], pp );
pp.setIndex(0);
}
writeDump( var: dirty );
writeDump( var: clean );
</cfscript>
SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. It allows for formatting (date -> text), parsing (text -> date), and normalization.
http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html
ParsePosition is a simple class used by Format and its subclasses to keep track of the current position during parsing.
http://docs.oracle.com/javase/1.4.2/docs/api/java/text/ParsePosition.html

Resources