I tried print(DateTime.now().millisecondsSinceEpoch); but it return a 13 digit number 1548070662432 , How can I get one like 1547897440?
This is an option:
(DateTime.now().millisecondsSinceEpoch / 1000).toInt();
This will give you the unix timestamp in secods.
You can use inbuilt method DateTime.utc as below:
static void getCurrentDateUTC() {
DateTime now = DateTime.utc(2021, 07, 23, 00, 00, 00);
int seconds = now.millisecondsSinceEpoch ~/ 1000;
print(seconds);
}
I have created the date manually. You can pass the params as you want.
Related
I have a time picker that returns the TimeOfDay object. But I have to save that value in a database as an integer of milliseconds which obtained from DateTime.millisecondsSinceEpoch. How can I achieve that?
This is not possible.
TimeOfDay holds only the hour and minute. While a DateTime also has day/month/year
If you want to convert it, you will need more information. Such as the current DateTime. And then merge the two into one final datetime.
TimeOfDay t;
final now = new DateTime.now();
return new DateTime(now.year, now.month, now.day, t.hour, t.minute);
You can use DateTime extension
extension DateTimeExtension on DateTime {
DateTime applied(TimeOfDay time) {
return DateTime(year, month, day, time.hour, time.minute);
}
}
then you can use it like this:
final dateTime = yourDate.applied(yourTimeOfDayValue);
and change your sdk version in pubspec.yaml to
environment:
sdk: ">=2.7.0 <3.0.0"
You can use entension like this and also can add some more extension methods in separate file like dateTime_extensions.dart to make your work easy for future projects as well
file: dateTime_extensions.dart;
extension DateTimeExtension on DateTime {
DateTime setTimeOfDay(TimeOfDay time) {
return DateTime(this.year, this.month, this.day, time.hour, time.minute);
}
DateTime setTime(
{int hours = 0,
int minutes = 0,
int seconds = 0,
int milliSeconds = 0,
int microSeconds = 0}) {
return DateTime(this.year, this.month, this.day, hours, minutes, seconds,
milliSeconds, microSeconds);
}
DateTime clearTime() {
return DateTime(this.year, this.month, this.day, 0, 0, 0, 0, 0);
}
///..... add more methods/properties for your convenience
}
use it like this
import 'package:your_app/dateTime_extensions.dart';
date.clearTime(); //to clear timeSpan
date.setTime(); //also be used to clear time if you don't provide any parameters
date.setTime(hours: 16,minutes: 23,seconds: 24); // will set time to existing date eg. existing_date 16:23:24
date.setTimeOfDay(TimeOfDay(hour: 16, minute: 59));
Here's just a tiny method to join a DateTime and a HourOfDay:
DateTime join(DateTime date, TimeOfDay time) {
return new DateTime(date.year, date.month, date.day, time.hour, time.minute);
}
You can set an extension on the TimeOfDay class:
extension TOD on TimeOfDay {
DateTime toDateTime() {
return DateTime(1, 1, 1, hour, minute);
}
}
then use it like this:
TimeOfDay timeOfDay = TimeOfDay.now();
DateTime dateTimeOfDay = timeOfDay.toDateTime();
if you define the extenson in another file and you have not imported it yet, if you are using vsc you can just type timeOfDay.toDateTime(); then ctrl + . and vsc will suggest importing that file. if you're not using vsc, then I guess you have to import the file of the extension manually.
How to parse relative datetime in GO?
Example of relative dates:
today at 9:17 AM
yesterday at 9:58 PM
Saturday at 9:44 PM
Wednesday at 11:01 AM
So format is DAY (in the past) at TIME. I tried next example:
const longForm = "Monday at 3:04 PM"
t, _ := time.Parse(longForm, "Saturday at 3:50 PM")
fmt.Println(t)
demo
Time is parsed correctly, but day/date is ignored...
Expanding on my comment:
Just Monday without further date reference is meaningless in the eyes of the parser, so it is discarded. Which Monday? The parser is strict, not fuzzy. Assuming Monday refers to the current week is not something that such a parser can do. You will not to write your own more sophisticated parser for that.
So it would have to be along these lines - one function that converts a relative fuzzy day to a real date, and replaces that in the original expression, and another one that parses the whole thing:
const dateFormat = "2006-01-02"
const longForm = "2006-01-02 at 3:04 PM"
func parseFuzzyDate(fuzzyTime string) (time.Time, error) {
formattedTime, err := parseDayAndReplaceIt(fuzzyTime)
if err != nil {
return nil, err
}
return time.Parse(longForm, formattedTime)
}
and the second function gets the fuzzy time, finds the day, parses it and returns. I'm not going to implement it, just write in comments what should be done:
func parseDayAndReplaceIt(fuzzyTime string) (string, error) {
// 1. Extract the day
// 2. Parse weekday names to relative time
// 3. if it's not a weekday name, parse things like "tomorrow" "yesterday"
// 4. replace the day string in the original fuzzyTime with a formatted date that the parser can understand
// 5. return the formatted date
}
I tweaked something that I wrote a while back and consolidated it into this example code:
func lastDateOf(targetDay time.Weekday, timeOfDay time.Time) time.Time {
const oneDay = 24 * time.Hour
var dayIndex time.Duration
//dayIndex -= oneDay
for {
if time.Now().Add(dayIndex).Weekday() == targetDay {
y, m, d := time.Now().Add(dayIndex).Date()
return timeOfDay.AddDate(y, int(m)-1, d-1)
}
dayIndex -= oneDay
}
}
It returns the date, relative to now, of the previous targetDay, added to timeOfDay, assuming that timeOfDay consists of hours, minutes and seconds, and the zero time values for year, month and day it will give you a suitable answer.
It's not very flexible but I believe it suits your example reasonably well. Although it doesn't address relative terms like "tomorrow", "yesterday" or "next Saturday".
runnable version in the playground.
Custom parser:
func RelativeDateParse(s string) (time.Time, error) {
for n := 0; n < 7; n++ {
day := time.Now().AddDate(0, 0, -n)
dayName := day.Format("Monday")
switch n {
case 0:
dayName = "today"
case 1:
dayName = "yesterday"
}
s = strings.Replace(s, dayName + " at", day.Format("2006-01-02"), -1)
}
return time.Parse("2006-01-02 3:04 PM", s)
}
demo
I have this dates here:
date1 = 2015-1-1
date2 = 2014-1-1
When I use this code:
int difference = date1.Value.Month - date2.Value.Month
This returns 0. I want the actual result to be 12 months since the date difference is within a year.
Someone help out? Completely new to this.
Try this code
DateTime date1 = Convert.ToDateTime("2015-1-1");
DateTime date2 = Convert.ToDateTime("2014-1-1");
Console.WriteLine((date1.Month - date2.Month) + 12 * (date1.Year - date2.Year));
var difference = date1.Value.Ticks - date2.Value.Ticks;
var dateDifference = new DateTime(difference);
int numberOfMonths = (dateDifference.Years * 12) + dateDifference.Months;
You can't get the exact result since day/years can change but you still
can try this:
//you can determine that the average month has 30.44 days (source:google)
const double daysToMonths = 30.4368499;
DateTime date1 = Convert.ToDateTime("2015-1-1");
DateTime date2 = Convert.ToDateTime("2014-1-1");
//round is optional here
Double Diff = Math.Round(date1.Subtract(date2).TotalDays/daysToMonths,0);
I resolved this issue by adding Microsoft.VisualBasic in my reference and by using the DateDiff function from Visual Basic. By using this, I don't need to manually compute the date anymore, I just set the interval and the 2 dates then it executes perfectly.
DateAndTime.DateDiff(DateInterval.Month, (DateTime)promoevent.TargetStartDate, (DateTime)promoevent.TargetEndDate);
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.
I have updated my project to version 2013.3.1324 from 2013.3.1119 (with ASP.NET MVC wrappers)
And I saw the following after update:
DateTime is passed to the client as
"/Date(-498283200000)/"
if less than 1970 year and
"/Date(498283200000)/"
if more that 1970 year
I have found a strange code in the kendo.all.js file
dateRegExp = /^\/Date\((.*?)\)\/$/,
tzOffsetRegExp = /[+-]{1}\d+/,
...
if (value && value.indexOf("/D") === 0) {
date = dateRegExp.exec(value);
if (date) {
date = date[1];
tzoffset = tzOffsetRegExp.exec(date);
date = parseInt(date, 10);
if (tzoffset) {
date -= (parseInt(tzoffset[0], 10) * kendo.date.MS_PER_MINUTE);
}
return new Date(date);
}
}
Debug info:
Initial value:
Parsed date value:
Parsed tzo value:
And finally, result date value:
Actually I don't need time, only Date. Model property type is regular DateTime.
Also I can't find any issues with this release on the Kendo site.
What I'm doing wrong and what I need to do? (changing Kendo source is not an option I think...)
Example:
Live demo: http://jsbin.com/vebed/2/edit?html,js,output
The following:
alert(kendo.parseDate("/Date(-498283200000)/"))
shows
Thu Mar 18 1954 22:00:00 GMT+0200 (FLE Standard Time)
with the latest official version of Kendo UI.
Make sure you are not using an older version.
Here is a live demo: http://jsbin.com/vebed/1/edit
Issue was fixed in the Internal build 2013.3.1408
New code is:
if (value && value.indexOf("/D") === 0) {
date = dateRegExp.exec(value);
if (date) {
tzoffset = date = date[1];
date = parseInt(date, 10);
tzoffset = tzoffset.substring(1).split(signRegExp)[1];
if (tzoffset) {
date -= (parseInt(tzoffset, 10) * kendo.date.MS_PER_MINUTE);
}
return new Date(date);
}
}