Converting timestamp - dart

I couldn't find a solution to this, I'm grabbing data from firebase and one of the fields is a timestamp which looks like this -> 1522129071. How to convert it to a date?
Swift example (works) :
func readTimestamp(timestamp: Int) {
let now = Date()
let dateFormatter = DateFormatter()
let date = Date(timeIntervalSince1970: Double(timestamp))
let components = Set<Calendar.Component>([.second, .minute, .hour, .day, .weekOfMonth])
let diff = Calendar.current.dateComponents(components, from: date, to: now)
var timeText = ""
dateFormatter.locale = .current
dateFormatter.dateFormat = "HH:mm a"
if diff.second! <= 0 || diff.second! > 0 && diff.minute! == 0 || diff.minute! > 0 && diff.hour! == 0 || diff.hour! > 0 && diff.day! == 0 {
timeText = dateFormatter.string(from: date)
}
if diff.day! > 0 && diff.weekOfMonth! == 0 {
timeText = (diff.day == 1) ? "\(diff.day!) DAY AGO" : "\(diff.day!) DAYS AGO"
}
if diff.weekOfMonth! > 0 {
timeText = (diff.weekOfMonth == 1) ? "\(diff.weekOfMonth!) WEEK AGO" : "\(diff.weekOfMonth!) WEEKS AGO"
}
return timeText
}
My attempt at Dart:
String readTimestamp(int timestamp) {
var now = new DateTime.now();
var format = new DateFormat('HH:mm a');
var date = new DateTime.fromMicrosecondsSinceEpoch(timestamp);
var diff = date.difference(now);
var time = '';
if (diff.inSeconds <= 0 || diff.inSeconds > 0 && diff.inMinutes == 0 || diff.inMinutes > 0 && diff.inHours == 0 || diff.inHours > 0 && diff.inDays == 0) {
time = format.format(date); // Doesn't get called when it should be
} else {
time = diff.inDays.toString() + 'DAYS AGO'; // Gets call and it's wrong date
}
return time;
}
And it returns dates/times that are waaaaaaay off.
UPDATE:
String readTimestamp(int timestamp) {
var now = new DateTime.now();
var format = new DateFormat('HH:mm a');
var date = new DateTime.fromMicrosecondsSinceEpoch(timestamp * 1000);
var diff = date.difference(now);
var time = '';
if (diff.inSeconds <= 0 || diff.inSeconds > 0 && diff.inMinutes == 0 || diff.inMinutes > 0 && diff.inHours == 0 || diff.inHours > 0 && diff.inDays == 0) {
time = format.format(date);
} else {
if (diff.inDays == 1) {
time = diff.inDays.toString() + 'DAY AGO';
} else {
time = diff.inDays.toString() + 'DAYS AGO';
}
}
return time;
}

Your timestamp format is in fact in Seconds (Unix timestamp) as opposed to microseconds. If so the answer is as follows:
Change:
var date = new DateTime.fromMicrosecondsSinceEpoch(timestamp);
to
var date = DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);

From milliseconds:
var millis = 978296400000;
var dt = DateTime.fromMillisecondsSinceEpoch(millis);
// 12 Hour format:
var d12 = DateFormat('MM/dd/yyyy, hh:mm a').format(dt); // 12/31/2000, 10:00 PM
// 24 Hour format:
var d24 = DateFormat('dd/MM/yyyy, HH:mm').format(dt); // 31/12/2000, 22:00
From Firestore:
Map<String, dynamic> map = docSnapshot.data()!;
DateTime dt = (map['timestamp'] as Timestamp).toDate();
Converting one format to other:
12 Hour to 24 Hour:
var input = DateFormat('MM/dd/yyyy, hh:mm a').parse('12/31/2000, 10:00 PM');
var output = DateFormat('dd/MM/yyyy, HH:mm').format(input); // 31/12/2000, 22:00
24 Hour to 12 Hour:
var input = DateFormat('dd/MM/yyyy, HH:mm').parse('31/12/2000, 22:00');
var output = DateFormat('MM/dd/yyyy, hh:mm a').format(input); // 12/31/2000, 10:00 PM
Use intl package (for formatting)

Full code for anyone who needs it:
String readTimestamp(int timestamp) {
var now = DateTime.now();
var format = DateFormat('HH:mm a');
var date = DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);
var diff = now.difference(date);
var time = '';
if (diff.inSeconds <= 0 || diff.inSeconds > 0 && diff.inMinutes == 0 || diff.inMinutes > 0 && diff.inHours == 0 || diff.inHours > 0 && diff.inDays == 0) {
time = format.format(date);
} else if (diff.inDays > 0 && diff.inDays < 7) {
if (diff.inDays == 1) {
time = diff.inDays.toString() + ' DAY AGO';
} else {
time = diff.inDays.toString() + ' DAYS AGO';
}
} else {
if (diff.inDays == 7) {
time = (diff.inDays / 7).floor().toString() + ' WEEK AGO';
} else {
time = (diff.inDays / 7).floor().toString() + ' WEEKS AGO';
}
}
return time;
}
Thank you Alex Haslam for the help!

if anyone come here to convert firebase Timestamp here this will help
Timestamp time;
DateTime.fromMicrosecondsSinceEpoch(time.microsecondsSinceEpoch)

If you are using firestore (and not just storing the timestamp as a string) a date field in a document will return a Timestamp. The Timestamp object contains a toDate() method.
Using timeago you can create a relative time quite simply:
_ago(Timestamp t) {
return timeago.format(t.toDate(), 'en_short');
}
build() {
return Text(_ago(document['mytimestamp'])));
}
Make sure to set _firestore.settings(timestampsInSnapshotsEnabled: true); to return a Timestamp instead of a Date object.

To convert Firestore Timestamp to DateTime object just use .toDate() method.
Example:
Timestamp now = Timestamp.now();
DateTime dateNow = now.toDate();
As you can see in docs

Just make sure to multiply by the right factor:
Micro: multiply by 1000000 (which is 10 power 6)
Milli: multiply by 1000 (which is 10 power 3)
This is what it should look like in Dart:
var date = new DateTime.fromMicrosecondsSinceEpoch(timestamp * 1000000);
Or
var date = new DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);

meh, just use https://github.com/andresaraujo/timeago.dart library; it does all the heavy-lifting for you.
EDIT:
From your question, it seems you wanted relative time conversions, and the timeago library enables you to do this in 1 line of code. Converting Dates isn't something I'd choose to implement myself, as there are a lot of edge cases & it gets fugly quickly, especially if you need to support different locales in the future. More code you write = more you have to test.
import 'package:timeago/timeago.dart' as timeago;
final fifteenAgo = DateTime.now().subtract(new Duration(minutes: 15));
print(timeago.format(fifteenAgo)); // 15 minutes ago
print(timeago.format(fifteenAgo, locale: 'en_short')); // 15m
print(timeago.format(fifteenAgo, locale: 'es'));
// Add a new locale messages
timeago.setLocaleMessages('fr', timeago.FrMessages());
// Override a locale message
timeago.setLocaleMessages('en', CustomMessages());
print(timeago.format(fifteenAgo)); // 15 min ago
print(timeago.format(fifteenAgo, locale: 'fr')); // environ 15 minutes
to convert epochMS to DateTime, just use...
final DateTime timeStamp = DateTime.fromMillisecondsSinceEpoch(1546553448639);

How to implement:
import 'package:intl/intl.dart';
getCustomFormattedDateTime(String givenDateTime, String dateFormat) {
// dateFormat = 'MM/dd/yy';
final DateTime docDateTime = DateTime.parse(givenDateTime);
return DateFormat(dateFormat).format(docDateTime);
}
How to call:
getCustomFormattedDateTime('2021-02-15T18:42:49.608466Z', 'MM/dd/yy');
Result:
02/15/21
Above code solved my problem. I hope, this will also help you. Thanks for asking this question.

I don't know if this will help anyone. The previous messages have helped me so I'm here to suggest a few things:
import 'package:intl/intl.dart';
DateTime convertTimeStampToDateTime(int timeStamp) {
var dateToTimeStamp = DateTime.fromMillisecondsSinceEpoch(timeStamp * 1000);
return dateToTimeStamp;
}
String convertTimeStampToHumanDate(int timeStamp) {
var dateToTimeStamp = DateTime.fromMillisecondsSinceEpoch(timeStamp * 1000);
return DateFormat('dd/MM/yyyy').format(dateToTimeStamp);
}
String convertTimeStampToHumanHour(int timeStamp) {
var dateToTimeStamp = DateTime.fromMillisecondsSinceEpoch(timeStamp * 1000);
return DateFormat('HH:mm').format(dateToTimeStamp);
}
int constructDateAndHourRdvToTimeStamp(DateTime dateTime, TimeOfDay time ) {
final constructDateTimeRdv = dateTimeToTimeStamp(DateTime(dateTime.year, dateTime.month, dateTime.day, time.hour, time.minute)) ;
return constructDateTimeRdv;
}

Assuming the field in timestamp firestore is called timestamp, in dart you could call the toDate() method on the returned map.
// Map from firestore
// Using flutterfire package hence the returned data()
Map<String, dynamic> data = documentSnapshot.data();
DateTime _timestamp = data['timestamp'].toDate();

Simply call this method to return your desired DateTime value in String.
String parseTimeStamp(int value) {
var date = DateTime.fromMillisecondsSinceEpoch(value * 1000);
var d12 = DateFormat('MM-dd-yyyy, hh:mm a').format(date);
return d12;
}
Example: if you pass the TimeStamp value 1636786003, you will get the result as
11-12-2021, 10:46PM

If you are here to just convert Timestamp into DateTime,
Timestamp timestamp = widget.firebaseDocument[timeStampfield];
DateTime date = Timestamp.fromMillisecondsSinceEpoch(
timestamp.millisecondsSinceEpoch).toDate();

I tested this one and it works
// Map from firestore
// Using flutterfire package hence the returned data()
Map<String, dynamic> data = documentSnapshot.data();
DateTime _timestamp = data['timestamp'].toDate();
Test details can be found here: https://www.youtube.com/watch?v=W_X8J7uBPNw&feature=youtu.be

Print DateTime, TimeStamp as string from Firebase Firestore:
Timestamp t;
String s;
DateTime d;
//Declaring Variables
snapshots.data.docs[index]['createdAt'] is Timestamp
? t = snapshots.data.docs[index]['createdAt']
: s =
snapshots.data.docs[index]['createdAt'].toString();
//check createdAt field Timestamp or DateTime
snapshots.data.docs[index]['createdAt'] is Timestamp
? d = t.toDate()
: s =
snapshots.data.docs[index]['createdAt'].toString();
print(s.toString()); //Print Date and Time if DateTime
print(d.toString()); //Print Date and Time if TimeStamp

Recently I've faced the same issue. so I'm using simple logic.
Very simple to Convert TimeStamp to DateTime. We can use this get TimeStamp to DateTime format.
In this example, I'm using Firebase.
import 'package:intl/intl.dart'; /// Import this line
TimeStamp timestamp = database.data()["date"] /// Firebase firestore date field value.
//Example Outputs:- Timestamp(seconds=1657706107, nanoseconds=261000000)
DateTime dateTime = timestamp.toDate(); /// It will be return Date and Time Both.
//Example Outputs:- 2022-07-13 15:25:07.261
String dateOnly = DateFormat('dd/MM/yyyy').format(dateTime); /// It will be only return date DD/MM/YYYY format
//Example Outputs:- 13/07/2022
In a single-line code
import 'package:intl/intl.dart'; /// Import this line
String dateOnly = DateFormat('dd/MM/yyyy').format(database.data()["date"].toDate()); /// It will be only return date DD/MM/YYYY format
//Example Outputs:- 13/07/2022
Thanks for visiting and pushing my reputation 😍
Happy Coding Journey...🤗

2022
Actually the Flutter team updated the Timestamp object.
Now if you want to convert from Timestamp to DateTime you can just use this code:
/*you Timestamp instance*/.toDate()
eg. Timestamp.now().toDate()
Viceversa if you want to convert from DateTime to Timestamp you can do:
Timestamp.fromDate(/*your DateTime instance*/)
eg. Timestamp.fromDate(DateTime.now())
Hope you'll find this helpfull.

All of that above can work but for a quick and easy fix you can use the time_formatter package.
Using this package you can convert the epoch to human-readable time.
String convertTimeStamp(timeStamp){
//Pass the epoch server time and the it will format it for you
String formatted = formatTime(timeStamp).toString();
return formatted;
}
//Then you can display it
Text(convertTimeStamp['createdTimeStamp'])//< 1 second : "Just now" up to < 730 days : "1 year"
Here you can check the format of the output that is going to be displayed: Formats

Timestamp has [toDate] method then you can use it directly as an DateTime.
timestamp.toDate();
// return DateTime object
Also there is an stupid way if you want really convert it:
DateTime.parse(timestamp.toDate().toString())

Long num format date into Calender format from:
var responseDate = 1637996744;
var date = DateTime.fromMillisecondsSinceEpoch(responseDate);
//to format date into different types to display;
// sample format: MM/dd/yyyy : 11/27/2021
var dateFormatted = DateFormat('MM/dd/yyyy').format(date);
// sample format: dd/MM/yyy : 27/11/2021
var dateFormatted = DateFormat('dd/MM/yyyy').format(date);
// sample format: dd/MMM/yyyy : 27/Nov/2021
var dateFormatted = DateFormat('dd/MMM/yyyy').format(date);
// sample format: dd/MMMM/yyyy : 27/November/2021
var dateFormatted = DateFormat('dd/MMMM/yyyy').format(date);
print("Date After Format = $dateFormatted");

Assuming you have a class
class Dtime {
int dt;
Dtime(this.dt);
String formatYMED() {
var date = DateTime.fromMillisecondsSinceEpoch(this.dt);
var formattedDate = DateFormat.yMMMMEEEEd().format(date);
return formattedDate;
}
String formatHMA() {
var time = DateTime.fromMillisecondsSinceEpoch(this.dt * 1000);
final timeFormat = DateFormat('h:mm a', 'en_US').format(time);
return timeFormat;
}
I am a beginner though, I hope that works.

There are different ways this can be achieved based on different scenario, see which of the following code fits your scenario.
Conversion of Firebase timestamp to DateTime:
document['timeStamp'].toDate()
(document["timeStamp"] as Timestamp).toDate()
DateTime.fromMillisecondsSinceEpoch(document['timeStamp'].millisecondsSinceEpoch);
Timestamp.fromMillisecondsSinceEpoch(document['timeStamp'].millisecondsSinceEpoch).toDate();
If timeStamp is in microseconds use:
DateTime.fromMicrosecondsSinceEpoch(timestamp * 1000000);
If timeStamp is in milliseconds use:
DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);
Add the following function in your dart file.
String formatTimestamp(Timestamp timestamp) {
var format = new DateFormat('yyyy-MM-dd'); // <- use skeleton here
return format.format(timestamp.toDate());
}
call it as formatTimestamp(document['timestamp'])

Related

How to compare two string values within a threshold value in swift?

I am trying to write a code where I have got two time[hh:min] data(String type). Need to just compare but the challenge is my code undergones some validations before returning the final values. so the assertion fails sometimes stating expected value is [17:04] but actual is [17:05]. Is there any way where we can use concept of Threshold that upto few minutes (say 2 mins) the comparison will still be valid?
Step one is do not store a thing as something that it is not. If these are times, they should be stored as times. Strings are for representation to the users; underlying storage is for reality.
So now let's store our times as date components:
let t1 = DateComponents(hour:17, minute:4)
let t2 = DateComponents(hour:17, minute:5)
Now it's easy to find out how far apart they are:
let cal = Calendar(identifier: .gregorian)
if let d1 = cal.date(from: t1),
let d2 = cal.date(from: t2) {
let diff = abs(d1.timeIntervalSince(d2))
// and now decide what to do
}
You first need to seprate your string to an array, and then you can compare.
/* That two arrays are A1 and A2 */
let minute1 = Int(A1[0])*60+Int(A1[1])
let minute2 = Int(A2[0])*60+Int(A2[1])
This may help you. I think that #Sweeper did not understand that it is a time, not a date.
You can convert your string to minutes, subtract one from another and check if the absolute value is less than the threshold:
extension String {
var time24hToMinutes: Int? {
guard count == 5, let hours = Int(prefix(2)), let minutes = Int(suffix(2)), Array(self)[2] == ":" else { return nil }
return hours * 60 + minutes
}
func time24hCompare(to other: String, threshold: Int = 2) -> Bool {
guard let lhs = time24hToMinutes, let rhs = other.time24hToMinutes else { return false }
return abs(lhs-rhs) < threshold
}
}
Testing:
"17:02".time24hCompare(to: "17:04") // false
"17:03".time24hCompare(to: "17:04") // true
"17:04".time24hCompare(to: "17:04") // true
"17:05".time24hCompare(to: "17:04") // true
"17:06".time24hCompare(to: "17:04") // false

Formatting a Duration like HH:mm:ss

Is there a good way to format a Duration in something like hh:mm:ss, without having to deal with time zones?
I tried this:
DateTime durationDate = DateTime.fromMillisecondsSinceEpoch(0);
String duration = DateFormat('hh:mm:ss').format(durationDate);
But I always get 1 hour to much, in this case it would say 01:00:00
And When I do this:
Duration(milliseconds: 0).toString();
I get this: 0:00:00.000000
You can use Duration and implement this method:
String _printDuration(Duration duration) {
String twoDigits(int n) => n.toString().padLeft(2, "0");
String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60));
return "${twoDigits(duration.inHours)}:$twoDigitMinutes:$twoDigitSeconds";
}
Usage:
final now = Duration(seconds: 30);
print("${_printDuration(now)}");
You can start creating a format yourself, come on this one:
String sDuration = "${duration.inHours}:${duration.inMinutes.remainder(60)}:${(duration.inSeconds.remainder(60))}";
The shortest, most elegant and reliable way to get HH:mm:ss from a Duration is doing:
format(Duration d) => d.toString().split('.').first.padLeft(8, "0");
Example usage:
main() {
final d1 = Duration(hours: 17, minutes: 3);
final d2 = Duration(hours: 9, minutes: 2, seconds: 26);
final d3 = Duration(milliseconds: 0);
print(format(d1)); // 17:03:00
print(format(d2)); // 09:02:26
print(format(d3)); // 00:00:00
}
Just a quick implementation.
This will display the Duration in [DD]d:[HH]h:[mm]m:[ss]s format, and will ignore the leading element if it was 0. But seconds will always present.
For example:
1d:2h:3m:4s
2h:3m:4s
3m:4s
4s
0s
/// Returns a formatted string for the given Duration [d] to be DD:HH:mm:ss
/// and ignore if 0.
static String formatDuration(Duration d) {
var seconds = d.inSeconds;
final days = seconds~/Duration.secondsPerDay;
seconds -= days*Duration.secondsPerDay;
final hours = seconds~/Duration.secondsPerHour;
seconds -= hours*Duration.secondsPerHour;
final minutes = seconds~/Duration.secondsPerMinute;
seconds -= minutes*Duration.secondsPerMinute;
final List<String> tokens = [];
if (days != 0) {
tokens.add('${days}d');
}
if (tokens.isNotEmpty || hours != 0){
tokens.add('${hours}h');
}
if (tokens.isNotEmpty || minutes != 0) {
tokens.add('${minutes}m');
}
tokens.add('${seconds}s');
return tokens.join(':');
}
Based on #diegoveloper's answer, I made it an extension which is also extendible
extension DurationExtensions on Duration {
/// Converts the duration into a readable string
/// 05:15
String toHoursMinutes() {
String twoDigitMinutes = _toTwoDigits(this.inMinutes.remainder(60));
return "${_toTwoDigits(this.inHours)}:$twoDigitMinutes";
}
/// Converts the duration into a readable string
/// 05:15:35
String toHoursMinutesSeconds() {
String twoDigitMinutes = _toTwoDigits(this.inMinutes.remainder(60));
String twoDigitSeconds = _toTwoDigits(this.inSeconds.remainder(60));
return "${_toTwoDigits(this.inHours)}:$twoDigitMinutes:$twoDigitSeconds";
}
String _toTwoDigits(int n) {
if (n >= 10) return "$n";
return "0$n";
}
}
Here's another version. It's all preference at this point, but I liked that it was dry and didn't need a function declaration (the wrapping function is obviously optional) though it is definately a bit function chaining heavy.
Compact
String formatTime(double time) {
Duration duration = Duration(milliseconds: time.round());
return [duration.inHours, duration.inMinutes, duration.inSeconds].map((seg) => seg.remainder(60).toString().padLeft(2, '0')).join(':');
}
Formatted version
String timeFormatter (double time) {
Duration duration = Duration(milliseconds: time.round());
return [duration.inHours, duration.inMinutes, duration.inSeconds]
.map((seg) => seg.remainder(60).toString().padLeft(2, '0'))
.join(':');
}
Define this:
extension on Duration {
String format() => '$this'.split('.')[0].padLeft(8, '0');
}
Usage:
String time = Duration(seconds: 3661).format(); // 01:01:01
Elaborating on other answers, here is an implementation that also formats days:
extension DurationFormatter on Duration {
/// Returns a day, hour, minute, second string representation of this `Duration`.
///
///
/// Returns a string with days, hours, minutes, and seconds in the
/// following format: `dd:HH:MM:SS`. For example,
///
/// var d = new Duration(days:19, hours:22, minutes:33);
/// d.dayHourMinuteSecondFormatted(); // "19:22:33:00"
String dayHourMinuteSecondFormatted() {
this.toString();
return [
this.inDays,
this.inHours.remainder(24),
this.inMinutes.remainder(60),
this.inSeconds.remainder(60)
].map((seg) {
return seg.toString().padLeft(2, '0');
}).join(':');
}
}
Unfortunately the intl package DateFormat class does not help: it marks the format of a Duration as not implemented:
formatDuration(DateTime reference) → String
NOT YET IMPLEMENTED. [...]
In my opinion the easiest way
String get refactoredDuration{
return Duration(seconds: duration).toString().split('.')[0];
}
You can use this:
print('${duration.inHours.toString().padLeft(2, '0')}:
${duration.inMinutes.remainder(60).toString().padLeft(2, '0')}:
${duration.inSeconds.remainder(60).toString().padLeft(2, '0')}');
I prefer thinking of Millisecond as its own unit, rather than as a subunit of something else. In that sense, it will have values of 0-999, so you're going to want to Pad three instead of two like I have seen with other answers. Here is an implementation:
String format(Duration o) {
var mil_s = (o.inMilliseconds % 1000).toString().padLeft(3, '0');
var sec_s = (o.inSeconds % 60).toString().padLeft(2, '0');
return o.inMinutes.toString() + ' m ' + sec_s + ' s ' + mil_s + ' ms';
}
https://api.dart.dev/dart-core/Duration-class.html
You can use this:
Text(RegExp(r'((^0*[1-9]\d*:)?\d{2}:\d{2})\.\d+$')
.firstMatch("$duration") ?.group(1) ?? '$duration'),
String myDuration(Duration duration) {
var date = duration.toString().split(":");
var hrs = date[0];
var mns = date[1];
var sds = date[2].split(".")[0];
return "$hrs:$mns:$sds";
}
Modified the first so when hours are in 00 it will not show.
extension VideoTimer on Duration {
String format() {
String twoDigits(int n) => n.toString().padLeft(2, '0');
final String twoDigitMinutes = twoDigits(inMinutes.remainder(60));
final String twoDigitSeconds = twoDigits(inSeconds.remainder(60));
final hour = twoDigits(inHours);
return "${hour == '00' ? '' : hour + ':'}$twoDigitMinutes:$twoDigitSeconds";
}
}
String _printDuration(Duration duration) {
String twoDigits(int n) => n.toString().padLeft(2, "0");
String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60));
return "$twoDigitMinutes:$twoDigitSeconds";
}
Container( //duration of video
child: Text("Total Duration: " + _printDuration(_controller.value.duration).toString()+" Position: " + _printDuration(_controller.value.position).toString()),
),

splitting date/time field to separate date and time

I have a date/time field (i.e. 2018-04-24 10:00:00) that I want to split into separate date and time. I have the following functions, but it does not work with uib-datepicker since I'm splitting a date/time field like a string:
function returnDate(date) {
var apptDate = date.split(' ')[0];
return apptDate;
}
function returnTime(date) {
var apptTime = date.split(' ')[1].substring(0,5);
var hours24 = parseInt(apptTime.substring(0, 2),10);
var hours = ((hours24 + 11) % 12) + 1;
var amPm = hours24 > 11 ? 'pm' : 'am';
var minutes = apptTime.substring(2);
return hours + minutes + ' ' + amPm;
}
I've also tried to use getDate, getFullYear, getMonth, etc. but I keep getting a TypeError with getDate.
Can someone provide some guidance on this date issue? Thanks!
Because between date and time it has a space, so you can get date and time separately by this way.
Method 1 : Split string
string date_time = "2018-04-24 10:00:00";
string[] words = date_time.Split(' ');//Split string
string date = words[0];//date = 1st object (before space)
string time = words[1];//time= 2nd object (after space)
Method 2 : Using Regular expression
string date_time = "2018-04-24 10:00:00";
string _date = "";
string _time = "";
Regex date = new Regex(#"([0-9-]+)\s");
Match match_date = date.Match(date_time);
Regex time = new Regex(#"\s([0-9:]+)");
Match match_time = time.Match(date_time);
//Date
if (match_date.Success)
{
_date = match_date.Value;
Console.WriteLine(_date);
}
//Time
if (match_time.Success)
{
_time = match_time.Value.Replace(" ","");
Console.WriteLine(_time);
}
have you tried new Date('2018-04-24 10:00:00') and then geting month year etc afterwords from a date object?

How to sort multiple array based on an array swift?

I would like to sort multiple array based on an array which is array of NSDate
var date = [NSDate]()
var name = [String]()
var job = [String]()
i would like to sort name and job based on the date. Example Like
date = [2016-04-02 01:03:42 +00002,2016-03-02 01:03:42 +0000,2016-05-02 01:03:42 +0000]
name = [john,alex,danson]
job = [engineer,programmer,swimmer]
i would like to sort the date from oldest to the latest then i would like to sort the name and job based on the date . Result Will be Like
date = [2016-03-02 01:03:42 +0000 ,2016-04-02 01:03:42 +0000 , 2016-05-02 01:03:42 +0000 ] //Being Sorted
name = [alex,john,danson]
job = [programmer,engineer,swimmer]
How can i do it ?
extension NSDate {
var day: Int { return NSCalendar.currentCalendar().components(.Day, fromDate: self).day }
}
let result = zip(zip(date, name), jobs).map { ($0.0.0, $0.0.1, $0.1) }.sort { $0.0.day < $1.0.day }
print(result)
This should do it. If you need an explanation, I'll try to explain.
If you want your existing array's to be sorted:
name = name.enumerate().sort { date[$0.index].day < date[$1.index].day }.map { $0.element }
jobs = jobs.enumerate().sort { date[$0.index].day < date[$1.index].day }.map { $0.element }
However, doing this is not safe because if the size of name or jobs is bigger than date, it will crash. You'll have to build some safety inside before using this.
What I forgot to mention is, you could also get the "original" arrays sorted by extracting it from result:
name = result.map { $0.1 }
jobs = result.map { $0.2 }
This is a programming problem instead of Swift problem.
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
let dateStrings = ["2016-03-02 01:04:42 +0000","2016-04-02 01:03:42 +0000" , "2016-05-02 01:03:42 +0000" ]
let date = dateStrings.map {
dateString in formatter.dateFromString(dateString)}
let name = ["alex","john","danson"]
let job = ["programmer","engineer","swimmer"]
let combine = date.enumerate().map {
index, date in
return (date!,name[index],job[index])
}
let result = combine.sort{
$0.0.compare($1.0) == NSComparisonResult.OrderedDescending
}

How to convert DateTime into different timezones?

How to convert DateTime into different timezones?
The DateTime class has two methods .toLocal() and .toUtc().
But if I want to display time in another time zone. How can I do it?
Here is my solution for EST time zone but you can change it to any other
import 'package:timezone/data/latest.dart' as tz;
import 'package:timezone/timezone.dart' as tz;
extension DateTimeExtension on DateTime {
static int _estToUtcDifference;
int _getESTtoUTCDifference() {
if (_estToUtcDifference == null) {
tz.initializeTimeZones();
final locationNY = tz.getLocation('America/New_York');
tz.TZDateTime nowNY = tz.TZDateTime.now(locationNY);
_estToUtcDifference = nowNY.timeZoneOffset.inHours;
}
return _estToUtcDifference;
}
DateTime toESTzone() {
DateTime result = this.toUtc(); // local time to UTC
result = result.add(Duration(hours: _getESTtoUTCDifference())); // convert UTC to EST
return result;
}
DateTime fromESTzone() {
DateTime result = this.subtract(Duration(hours: _getESTtoUTCDifference())); // convert EST to UTC
String dateTimeAsIso8601String = result.toIso8601String();
dateTimeAsIso8601String += dateTimeAsIso8601String.characters.last.equalsIgnoreCase('Z') ? '' : 'Z';
result = DateTime.parse(dateTimeAsIso8601String); // make isUtc to be true
result = result.toLocal(); // convert UTC to local time
return result;
}
}
DateTime doesn't contain timezone information therefore you can't create a DateTime in a specific timezone only the timezone of your system and UTC are available.
You can wrap the DateTime in a custom class and add timezone information to the wrapper. You also need a table of offsets for each timezone and then add/substract the offset from the UTC date.
I wrote a package for this. It's called Instant, and it can convert a DateTime in any given timezone worldwide. Take a detailed look at https://aditya-kishore.gitbook.io/instant/
The basic usage for converting a DateTime to a timezone is very simple:
//Assumes Instant is in your pubspec
import 'package:instant/instant.dart';
//Super Simple!
DateTime myDT = DateTime.now(); //Current DateTime
DateTime EastCoast = dateTimeToZone(zone: "EST", datetime: myDT); //DateTime in EST zone
return EastCoast;
This works with one line of code and minimal hassle.
You can use an external package, like: timezone.
See docs here: https://pub.dev/packages/timezone
Here's a sample code to get the time in Los Angeles (PST/PDT).
import 'package:timezone/timezone.dart' as tz;
import 'package:timezone/data/latest.dart' as tz;
DateTime _getPSTTime() {
tz.initializeTimeZones();
final DateTime now = DateTime.now();
final pacificTimeZone = tz.getLocation('America/Los_Angeles');
return tz.TZDateTime.from(now, pacificTimeZone);
}
import 'package:timezone/timezone.dart'
String locationLocal = await FlutterNativeTimezone.getLocalTimezone();
//Esta Função recebe uma data/hora e converte para data/hora local.
TZDateTime convertFireBaseToLocal(TZDateTime tzDateTime, String locationLocal) {
TZDateTime nowLocal = new TZDateTime.now(getLocation(locationLocal));
int difference = nowLocal.timeZoneOffset.inHours;
TZDateTime newTzDateTime;
newTzDateTime = tzDateTime.add(Duration(hours: difference));
return newTzDateTime;
}
I modified Boris answer to pretend as user is in EST, otherwise time is adjusted to UTC:
import 'package:timezone/data/latest.dart' as tz;
import 'package:timezone/timezone.dart' as tz;
extension DateTimeExtension on DateTime {
static int? _estToUtcDifference;
int _getESTtoUTCDifference() {
if (_estToUtcDifference == null) {
tz.initializeTimeZones();
final locationNY = tz.getLocation('America/New_York');
tz.TZDateTime nowNY = tz.TZDateTime.now(locationNY);
_estToUtcDifference = nowNY.timeZoneOffset.inHours;
}
return _estToUtcDifference!;
}
DateTime toESTzone() {
DateTime result = toUtc(); // local time to UTC
result = result.add(Duration(hours: _getESTtoUTCDifference()));
// convert UTC to EST and remove ZULU as it is not UTC anymore.
String dateTimeAsIso8601String =
result.toIso8601String().replaceAll('Z', '');
result = DateTime.parse(dateTimeAsIso8601String);
return result;
}
DateTime fromESTzone() {
DateTime result = subtract(
Duration(hours: _getESTtoUTCDifference())); // convert EST to UTC
String dateTimeAsIso8601String = result.toIso8601String();
dateTimeAsIso8601String += dateTimeAsIso8601String.endsWith('Z') ? '' : 'Z';
result = DateTime.parse(dateTimeAsIso8601String); // make isUtc to be true
result = result.toLocal(); // convert UTC to local time
return result;
}
}
Convert To IST for example, if not interested to use any non-verified lib in production.
DateTime.now().toUtc().add(const Duration(hours: 5, minutes: 30));
use simple EPOC time istead of other stuff
var now = DateTime.now().millisecondsSinceEpoch;
You can use TimeZoneInfo.ConvertTime() to change timezone. Try like this
DateTime hwTime = new DateTime(2007, 02, 01, 08, 00, 00);
try {
TimeZoneInfo hwZone = TimeZoneInfo.FindSystemTimeZoneById("Hawaiian Standard Time");
TimeZoneInfo.ConvertTime(hwTime, hwZone, TimeZoneInfo.Local));
}
catch (TimeZoneNotFoundException) {
Console.WriteLine("Timezone not found");
}
catch (InvalidTimeZoneException) {
Console.WriteLine("Invalid Timezone");
}
This will convert from Hawaiian Standard Time to Local.
It is just an example. Use it to convert as per your need.

Resources