I want to add offset GMT +05:30 to Time but I don't know how to do that
String offset = data ['utc_offset'].substring(1,);
ntime =ntime.add(Duration(hours:int.parse(offset)));
Since there is " : " in the middle of 05:30 I can't add the exact value..
PS: I'm using http://worldtimeapi.org JSON API
You can parse the offset time by using a RegExp. I have used named groups in my example since I finds it more simple to understand what each part of the regexp are extracting:
import 'dart:io';
void main() {
const offset = '+01:00';
final regexp =
RegExp(r'^(?<plusMinus>[+-]?)(?<hours>[\d]+):(?<minutes>[\d]+)');
final match = regexp.firstMatch(offset);
print(match.namedGroup('plusMinus'));
print(match.namedGroup('hours'));
print(match.namedGroup('minutes'));
final offsetDuration = Duration(
hours: int.parse(match.namedGroup('hours')),
minutes: int.parse(match.namedGroup('minutes')));
DateTime time;
if (match.namedGroup('plusMinus') == '+') {
time = DateTime.now().add(offsetDuration);
} else if (match.namedGroup('plusMinus') == '-') {
time = DateTime.now().subtract(offsetDuration);
} else {
time = DateTime.now();
}
print(time);
}
Related
I have a function here that gets the date, and adds one week to it:
func thingy() {
let currentDate = Date()
var dateComponent = DateComponents()
dateComponent.day = 7
let futureDate = Calendar.current.date(byAdding: (dateComponent*i), to: currentDate)
print(futureDate!.formatted())
}
This gets the current date, adds one week to it, and prints out that date.
I want to get a for loop that will give the date, for example maybe 10 weeks in the future, maybe looking something like this:
for i in 1...num[ex: 11] {
let currentDate = Date()
var dateComponent = DateComponents()
dateComponent.day = 7
let futureDate = Calendar.current.date(byAdding: (dateComponent*i), to: currentDate)
let match = (title: "Test", date: futureDate)
}
I get this error:
Referencing operator function '*' on 'DurationProtocol' requires that 'DateComponents' conform to 'DurationProtocol'
How do I fix this?
I would advise adding .weekOfYear to the date. E.g., to get an array of Date representing the next ten weeks:
let calendar = Calendar.current
let today = calendar.startOfDay(for: Date())
let dates = (1 ... 10)
.compactMap { calendar.date(byAdding: .weekOfYear, value: $0, to: today) }
I am currently exporting data from Grafana. I do that using a script which looks like this one:
JsonSlurper slurper = new JsonSlurper()
println "Collect list of servers:"
def result = slurper.parse(new URL('http://xyz'))
def servers = [:].withDefault { [] }
result.data.each{ it ->
servers[it.server] = "${it.server};${it.app};${it.team}"
}
servers.sort().each { k, v -> println v}
println "Collect data for servers:"
Date currentDate = new Date();
Date fromDate = currentDate - 30
long unixTimeNow = currentDate.getTime() / 1000
long unixFromDate = fromDate.getTime() / 1000
long stepSec = 7200
boolean header = true
servers.sort().each{ server, label ->
File resultFile = new File("C:\\Users\\GrafanaExport${server}.csv")
if(resultFile.exists()) {
resultFile.delete()
}
def queries = [
['node_load1',"http://abc{server}.start${unixFromDate}&end=${unixTimeNow}&step=${stepSec}"],]
def resultTable = [:].withDefault { [";",";",";"] }
queries.eachWithIndex { q, i ->
println(q)
result = slurper.parse(new URL(q[1]))
result?.data?.result[0]?.values?.each{ it ->
resultTable[it[0]][i] = it[1] + ";"
}
}
if(header) {
resultFile << "timestamp;" + queries.collect{it[0]}.join(';') + '\n'
header = false
}
resultFile << label + '\n'
resultTable.sort().each { k, v ->
resultFile << "${k};${v.join('')}\n"
}
}
This works fine but what I want to get instead is not the data from now until some time ago but from a certain timestamp until some time ago. Because previously I already exported data and I would like to get the same dates/timestamps for the data. The previously exported data is stamped with this timestamps (snip of the example timestamps):
That means the data was exported every two hours (because of this a step of 7200 seconds) and at every full and in unix time every even hour. I now want to know how I need to amend my code in order to get the data for the same timestamps as before?
Thanks a lot!
This question already has answers here:
How do I convert a date/time string to a DateTime object in Dart?
(8 answers)
Closed 1 year ago.
I am trying to parse String formatted like "23.1.2020" to DateTime object, but nothing works for me. I tried to use some packages like intl or date_format, but none of these can do the job.
DateTime todayDate = DateTime.parse("12.04.2020");
formatDate(todayDate, [yyyy, '/', mm, '/', dd, ' ', hh, ':', nn, ':', ss, ' ', am])
Do you have any idea, how to parse this?
Ok, I found way how to do that:
import 'package:intl/intl.dart';
DateFormat format = DateFormat("dd.MM.yyyy");
print(format.parse(date));
If you are absolutely sure that your date format will always be "dd.MM.yyyy" you could do this :
DateTime todayDate = DateTime.parse("12.04.2020".split('.').reversed.join());
This trick will format your date to "yyyyMMdd" format, which, according to the docs, is accepted by DateTime.parse().
Try out this package, Jiffy, it also runs on top of Intl, but makes it easier using momentjs syntax. See below
var date = Jiffy("12.04.2020", "dd.MM.yyyy").format("dd, Oct yy"); // 12, Apr 20
You can also do the following default formats
var date = Jiffy("12.04.2020", "dd.MM.yyyy").yMMMMd; // April 12, 2020
Hope this helps
Fuction Convert date to string :
String dateTostring(DateTime datevalue)
{
String _stringdate ="";
_stringdate = datevalue.month.toString()+"."+datevalue.day.toString()+"."+datevalue.year.toString() ;
return _stringdate;
}
Then fuction convert string to date:
DateTime dateStringtodate(String stringdate)
{
DateTime _stringdate;
List<String> validadeSplit = stringdate.split('.');
if(validadeSplit.length > 1)
{
int day = int.parse(validadeSplit[1].toString()));
int month = int.parse(validadeSplit[0].toString());
int year = int.parse(validadeSplit[2].toString());
_stringdate = DateTime.utc(year, day, month);
}
return _stringdate;
}
I have to find the difference between two times in 24 hour format. I have the two time strings, Eg: 10:40 and 18:20. How can I find the difference between these two times in Flutter?
You can use intl package.
var format = DateFormat("HH:mm");
var one = format.parse("10:40");
var two = format.parse("18:20");
print("${two.difference(one)}"); // prints 7:40
A complete answer for perfect calculation is given bellow
String start_time = formateTime('12:00'); // or if '24:00'
String end_time = formateTime('24:00'); // or if '12:00
var format = DateFormat("HH:mm");
var start = format.parse(start_time);
var end = format.parse(end_time);
if (start.isAfter(end)) {
print('start is big');
print('difference = ${start.difference(end)}');
} else if(start.isBefore(end)){
print('end is big');
print('difference = ${end.difference(start)}');
}else{
print('difference = ${end.difference(start)}');
}
Programming in Flex 4.5
I'm getting a date as a String.
I don't know what date or hour I'm getting.
I want to convert the string to date and take only the hours & minutes.
For example:
Getting - "2012-02-07T13:35:46+02:00"
I want to see: 13:35.
Suggestions or any other solutions?
After some digging, Solution:
var myDate:Date;
myDate = DateFormmater.parseDateString(myDateString);
var dateResult:String = myDate.getHours() + ":" + myDate.getMinutes();
Thanks anyway! :-)!
You can to use date.getHours() and date.getMinutes(). Try the following:
var d:Date = DateField.stringToDate("your_date_string","YYYY-MM-DD");
trace("hours: ", date.getHours()); // returns 13
trace("minutes: ", date.getMinutes()); // returns 35
private function init():void
{
var isoStr:String = "2012-02-07T13:35:46+02:00";
var d:Date = new Date;
d = isoToDate(isoStr)
trace(d.hours);
}
private function isoToDate(value:String):Date
{
var dateStr:String = value;
dateStr = dateStr.replace(/\-/g, "/");
dateStr = dateStr.replace("T", " ");
dateStr = dateStr.replace("+02:00", " GMT-0000");
return new Date(Date.parse(dateStr));
}
I see you've already got the answer, but for future users, here it is.
var myDateString:String="2012-02-07T13:35:46+02:00"
//This is of the format <yyyy-mm-dd>T<hh:mm:ss><UTC-OFFSET AS hh:mm>
//You could write your own function to parse it, or use Flex's DateFormatter class
var myDate:Date=DateFormatter.parseDateString(myDateString);
//Now, myDate has the date as a Flex Date type.
//You can use the various date functions. In this case,
trace(myDate.getHours()); //Traces the hh value
trace(myDate.getMinutes()); //Traces the mm value