Related
How to disable the past dates in the Kendo date picker ? ( Date Picker validation)
That will allow the user to select only the current date and future date.
In the HTML :
#Html.EditorFor(Model => Model.AppointmentDate)
In the JQuery :
$('#AppointmentDatee').data('kendoDatePicker')
The shortest way to disable past dates is using min parameter with current date value:
var presentDate = new Date();
$(function () {
var datepicker = $('#AppointmentDate').kendoDatePicker({
value: presentDate,
min: presentDate,
}).data('kendoDatePicker');
});
If you're using Razor with #Html.Kendo() helper, use DatePickerBuilderBase.Min() method:
#(Html.Kendo().DatePicker().Name("AppointmentDate").Min(DateTime.Today))
However, the min parameter will remove all disabled past dates (i.e. they're not shown in calendar view). If you want to show disabled dates but the user cannot interact with them (by clicking the date), use k-state-disabled CSS class in empty option inside month parameter:
var datepicker = $('#AppointmentDate2').kendoDatePicker({
value: presentDate,
min: presentDate,
month: {
empty: '<div class="k-state-disabled">#= data.value #</div>'
}
}).data('kendoDatePicker');
If #(Html.Kendo()) helper is used, use DisabledDates to call a function which disables past dates like example below:
<script>
var getPastDates = function(begin, end) {
for (var dtarr = [], date = start; date < end; date.setDate(date.getDate() + 1)) {
dtarr.push(new Date(dt));
}
return dtarr;
}
function disablePastDates(date) {
var pastDate = getPastDates(new Date('0001-01-01T00:00:00Z'), new Date());
if (date && compareDates(date, dates)) {
return true;
}
else {
return false;
}
}
function compareDates(date, dates) {
for (var i = 0; i < dates.length; i++) {
if (dates[i].getDate() == date.getDate() &&
dates[i].getMonth() == date.getMonth() &&
dates[i].getYear() == date.getYear()) {
return true;
}
}
}
</script>
Helper usage:
#(Html.Kendo().DatePicker().Name("AppointmentDate").DisableDates("disablePastDates"))
Working examples:
JSFiddle demo 1 (hidden past dates)
JSFiddle demo 2 (grayed-out past dates)
References:
Kendo.Mvc.UI.Fluent.DatePickerBuilderBase.Min(DateTime)
Show Out-of-Range Dates as Disabled
Kendo MVC DatePicker - Disable dates
Similar issue (with different approach):
How to disable past dates without hiding them in Kendo date picker?
if you use jquery for your kendoDatePicker , this code may help you!
$("#MyDatapickerElement").kendoDatePicker({
value: new Date(),
disableDates: function (date) {
if (date <= new Date()) {
return true;
} else {
return false;
}
}
});
If using Html.Kendo().DatePicker() you can show the disabled dates using the MonthTemplate. Example below shows the Minimum Date set to DateTime.Today and sets the MonthTemplate to show past dates as disabled.
Html.Kendo().DatePicker()
.Name("MyDate")
.Min(DateTime.Today)
.MonthTemplate(m=>m
.Empty("<div class=\"k-state-disabled\">#= data.value #</div>")
)
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'])
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);
I'm facing an issue with date timezoning missed between AngularJS and Entity Framework.
This is a sample of my angular code: PLNKR
I get date from server side (ASP.NET MVC5) as string like this: "2015-02-17T00:00:00" without any info about timezone.
To parse this string as date and bind it to input[date], I'm using angularjs directive for this.
My problem is: my local timezone is +4, after changing the value and pushing it back to the ngModel, it is converted to UTC time, so date part will be -1 day back. In other words, if I select Feb 18, 2015 in the date input, the ngModel value will be: 2015-02-17T20:00:00.000Z. So, when passed back to the server, I receive it in the controller like this:
{5/17/1988 8:00:00 PM}
Date: {5/17/1988 12:00:00 AM}
dateData: 5238841010427387904
Day: 17
DayOfWeek: Tuesday
DayOfYear: 138
Hour: 20
InternalKind: 4611686018427387904
InternalTicks: 627154992000000000
Kind: Utc
Millisecond: 0
Minute: 0
Month: 5
Second: 0
Ticks: 627154992000000000
TimeOfDay: {20:00:00}
Year: 1988
The kind of this date is Utc. But when I pass it to the DB throught Entity framework (v6) it is saved without any timezoning. So, next time I'm loading it, it will be in local timezone, so with -4 hours from the original value, which is wrong.
This date attribute in entity framework model is simple, just like this public DateTime BirthDate { get; set; } and in DB (MSSQL) it is of type DateTime like this: [BirthDate] DATETIME NOT NULL
I think the solution should be: either to force Angular to use only local timezone, while my application will run only locally, or to force entity framework to save timezone info.
I prefer to go with first option, but how?
I solved this issue by changing the return type of angularJS directive from Date object to string with yyyy-mm-dd format.
Before:
(function() {
function parseDateString(dateString) {
if ('undefined' === typeof dateString || '' === dateString) {
return null;
}
var parts = dateString.split('-');
var year = parseInt(parts[0], 10);
var month = parseInt(parts[1], 10);
var day = parseInt(parts[2], 10);
return new Date(year, (month - 1), day);
}
var mainApp = angular.module('mainApp', [])
.directive('input', ['dateFilter',
function(dateFilter) {
return {
restrict: 'E',
require: '?ngModel',
link: function(scope, element, attrs, ngModel) {
if ('undefined' !== typeof attrs.type && 'date' === attrs.type && ngModel) {
ngModel.$formatters = [ function(modelValue) { return dateFilter(modelValue, 'yyyy-MM-dd'); } ];
ngModel.$parsers = [ function(viewValue) { return parseDateString(viewValue); } ];
}
}
}
}
]).controller("myController", function($scope) {
$scope.testDate = "2015-02-17T00:00:00";
});
}());
After:
(function() {
var mainApp = angular.module('mainApp', [])
.directive('input', ['dateFilter',
function(dateFilter) {
return {
restrict: 'E',
require: '?ngModel',
link: function(scope, element, attrs, ngModel) {
if ('undefined' !== typeof attrs.type && 'date' === attrs.type && ngModel) {
ngModel.$formatters = [
function(modelValue) {
return dateFilter(modelValue, 'yyyy-MM-dd');
}
];
ngModel.$parsers = [
function(viewValue) {
return dateFilter(modelValue, 'yyyy-MM-dd');
}
];
}
}
}
}
]).controller("myController", function($scope) {
$scope.testDate = "2015-02-17T00:00:00";
});
}());
I've been fighting this problem for most of the day now, so I figure I'd ask here...
I'm creating a plot using highcharts, and I want to use a datetime xAxis. The label I wish to show on this axis is a calculated value, relative to a set of specific dates. So I use a labels.formatter function which have access to the previous and the last dates, and relative to these dates I do some logics.
The logic is that if this.value (from within the formatter) is before the last one, the axis should show months since previous ones, if this.value == last it should show 0 and if this.value > last it should show months since last.
I have some helper functions that are called in my code, they have been used in many occasions and work as they should.
Below is the implementation of my label formatter for the xAxis.
gVars.reportAddedResistance.MonthSinceUsed = new Array();
this.highchart.options.xAxis.labels.formatter = function() {
var mbDec;
var mod;
var result;
var returnValue = null;
var isSet;
var previous = new Date(self.data.plotConf.previousDrydockDate);
var last = new Date(self.data.plotConf.lastDrydockDate);
var val = new Date(this.value);
if(val.getTime() < last.getTime()) {
// BEFORE LAST DRYDOCK
mbDec = Utils.monthsBetweenDecimal(previous, val);
mod = mbDec % 1;
if(mod <= (1 / 30.4375)) {
result = Math.round(mbDec);
isSet = gVars.reportAddedResistance.MonthSinceUsed.indexOf(result);
if(isSet == -1) {
gVars.reportAddedResistance.MonthSinceUsed.push(result);
//console.log('',"LESS Returning "+result+" Used: "+gVars.reportAddedResistance.MonthSinceUsed);
returnValue = result;
}
}
}
else if(val.getTime() == last.getTime()){
// AT LAST DRYDOCK
var result = 0;
isSet = gVars.reportAddedResistance.MonthSinceUsed.indexOf(result);
if(isSet == -1) {
gVars.reportAddedResistance.MonthSinceUsed.push(result);
//console.log('',"EVEN Returning "+result+" Used: "+gVars.reportAddedResistance.MonthSinceUsed);
returnValue = result;
}
}
else if(val.getTime() > last.getTime()){
// AFTER LAST DRYDOCK
mbDec = Utils.monthsBetweenDecimal(last, val);
mod = mbDec % 1;
if(mod <= (1 / 30.4375)) {
result = Math.round(mbDec);
isSet = gVars.reportAddedResistance.MonthSinceUsed.indexOf(result);
if(isSet == -1) {
gVars.reportAddedResistance.MonthSinceUsed.push(result);
//console.log('',"MORE Returning "+result+" Used: "+gVars.reportAddedResistance.MonthSinceUsed);
returnValue = result;
}
}
}
return returnValue;
};
The value of previous is (from console.log):
Date {Tue Jun 15 2010 02:00:00 GMT+0200 (Romance Daylight Time)}
The value of last is (from console.log):
Date {Sat Jun 15 2013 02:00:00 GMT+0200 (Romance Daylight Time)}
If I enable the console.log output I get this output, which to me indicates that the logics and date comparisons is working as expected:
LESS Returning 31 Used: 31
LESS Returning 32 Used: 31,32
LESS Returning 33 Used: 31,32,33
LESS Returning 34 Used: 31,32,33,34
LESS Returning 35 Used: 31,32,33,34,35
EVEN Returning 0 Used: 31,32,33,34,35,0
MORE Returning 1 Used: 31,32,33,34,35,0,1
MORE Returning 2 Used: 31,32,33,34,35,0,1,2
MORE Returning 3 Used: 31,32,33,34,35,0,1,2,3
MORE Returning 4 Used: 31,32,33,34,35,0,1,2,3,4
MORE Returning 5 Used: 31,32,33,34,35,0,1,2,3,4,5
MORE Returning 6 Used: 31,32,33,34,35,0,1,2,3,4,5,6
MORE Returning 7 Used: 31,32,33,34,35,0,1,2,3,4,5,6,7
MORE Returning 8 Used: 31,32,33,34,35,0,1,2,3,4,5,6,7,8
My problem is, that the returned values are not displayed on my plot. If I change the formatter function to just return this.value it displays them all, without any problems, but for some reason I cannot identify the return values (as seen in the above console.log output) is not shown.
My xAxis is configured like this:
xAxis: {
type : 'datetime',
dateTimeLabelFormats: {
day: '%Y-%m-%d',
week: '%Y-%m-%d',
month: '%Y-%m-%d',
year: '%Y-%m'
},
startOnTick : false,
tickInterval : 24 * 3600 * 1000 * 1, // 1 day
title : {
text : 'Months relative to drydockings',
style : {
fontSize : '9pt',
fontFamily : 'Arial'
}
},
labels : {
maxStaggerLines : 1,
style : {
fontSize : '7pt',
fontFamily : 'Arial'
}
}
},
I'm stuck - PLEASE HELP!!! :-)
EDIT: I'm using Highcharts JS v3.0.7 (2013-10-24)
The solution to my problem was to add this to the formatter:
if(this.isFirst) {
gVars.noOfSeriesCalled++;
}
if(gVars.noOfSeriesCalled == this.axis.series.length) {
// The stuff thats posted above
}
else {
return null;
}
I think its an error in the library that I have to use a global variable to keep track of how many iterations I've been through.
The correct implementation, as seen from my perspective, would be that the formatting function were called once for each tick in the xAxis, regardless of how many series are added to the plot.