Parsing the hour only - javascript

I'm using d3 v3 to parse some intraday data that has the following format:
time,value
09:00,1
09:05,2
09:10,3
...
So I set up a parsing variable like so:
var parseTime = d3.time.format("%H:%M").parse;
And I map the data within the scope of the csv call:
d3.csv("my_data.csv", function(error, rawData) {
var data = rawData.map(function(d) {
return {y_value: +d.value, date: parseTime(d.time)}
});
console.log(data)
}
In the console, I get something strange. Instead of only the hour, I get the full-fledged date, day of the week, month, even time zone.
data->
array[79]
0:Object->
date: Mon Jan 01 1900 09:00:00 GMT+0000
y_value: 1
Do dates need to be this complete? I suppose that could explain why I wound up with monday Jan. 1st, seems like a default of sorts. However, according to d3 time documentation, "%H:%M" is used for hours and minutes. And I could have sworn I did that much correct.
I know something is not quite right because my line graph is throwing the error:
error: <path> attribute d: expected number "MNaN"
My best guess is that the date is over-specified and the axis() is expecting an hour format.
My Question is: Why isn't my data being parsed as hour only? Should I change this from the parsing end? If that's not an option, can I have the x domain read a portion of the date (the hour and minute portion)?
Update: Here is a minimal block for further illustration of my plight.

When you say...
why isn't my data being parsed as hour only?
... it becomes evident that there is a basic misunderstanding here. Let's clarify it.
What is a date?
Simply put, a date is a moment in time. It can be now, or two months ago, or the day my son was born, or next Christmas, or the moment Socrates drank the hemlock. It does'n matter. What is important to understand is that all those dates have a century, a decade, a year, a month, a day, an hour, a minute, a second, a millisecond etc... (of course, those names are conventions that can be changed).
Therefore, it makes little sense having a date with just the hour, or just the hour and the minute.
Parsing and formating
When you parse a string, you create a date object. As we explained above, that date object corresponds to a moment in time, and it will have year, month, hour, timezone etc... If the string itself lacks some information, as year for instance, it will default to some value.
Look at this demo, we will parse a string into a date object, using the correct specifier:
var string = "09:00";
var parser = d3.timeParse("%H:%M");
var date = parser(string);
console.log("The date object is: " + date);
<script src="https://d3js.org/d3.v4.min.js"></script>
As you can see, we have a date object now. By the way, you can see that it defaults to a given year (1900), a given month (January), and so on...
However, in your chart, you don't need to show the entire object, that is, all the information regarding that moment in time. You can show just hour and minute, for instance. We will format that date.
Have a look:
var string = "09:00";
var parser = d3.timeParse("%H:%M");
var format = d3.timeFormat("%H:%M");
var date = parser(string);
console.log("The date object is: " + date);
console.log("The formatted date is: " + format(date));
<script src="https://d3js.org/d3.v4.min.js"></script>
That formatted date is useful for creating axes, tooltips, texts etc..., that is, showing the date you have without showing all its details. You can choose what information you want to show to the user (just the year, or just the month, or maybe day-month-year, whatever).
That's the difference between parsing and formatting.
Why using a formatter?
To finalise, you may ask: why am I using a formatter, if I will end up having the same thing I had at the beginning?
The answer is: you don't have the same thing. Now you have a date, not a string. And, using a date with a time scale, you can accomodate daylight savings, leap years, February with only 28 days, that is, a bunch of things that are impossible to do with a simple string.
PS: The demos above use D3 v4.
EDIT: After your update we can easily see the problem with your code: you have to pass an array to range().
var xScale = d3.time.scale().range([0,width]);
Here is the updated bl.ocks: http://bl.ocks.org/anonymous/a05e15339f7792f175d2bcebccf6bbed/7f23db481f1308eb0d5a1834f7cbc0b17d948167

Related

Inconsistency when converting DateTime to JavaScript

I have a ASP.NET webapi with a DateTimeZoneHandling set to Local and I am getting two different results when converting to a JavaScript date.
Example 1
Date returned from server 1932-10-13T00:00:00-04:00
var strDate = new Date("1932-10-13T00:00:00-04:00");
strDate.toISOString(); // 1932-10-13T04:00:00.000Z
strDate.toLocaleString(); // 10/12/1932, 11:00:00 PM
Example 2
Date returned from server 2013-05-09T00:00:00-04:00
var strDate = new Date("2013-05-09T00:00:00-04:00");
strDate.toISOString(); // 2013-05-09T04:00:00.000Z
strDate.toLocaleString(); // 5/9/2013, 12:00:00 AM
I expected behaviour should always be midnight as the dates returned from the server are always midnight. It appears all recent dates parse correctly, however, dates far in the past are incorrect.
The timezone can vary in some locales, for example, I'm UTC-0300, and on certain season shifts it becomes UTC-0200, so it indicates that your locale changed the offset too, making it display the time one hour lesser, basicaly because you locale adopted a different offset along the year.
The example bellow, I've changed your first example to use the same day and month than the second one, so that it proves you that old dates has nothing to do with it.
console.log("Example One");
var strDate = new Date("1932-05-09T00:00:00-04:00");
console.log(strDate.toISOString());
console.log(strDate.toLocaleString());
console.log("--------------------------");
console.log("Example Two");
var strDate2 = new Date("2013-05-09T00:00:00-04:00");
console.log(strDate2.toISOString());
console.log(strDate2.toLocaleString());
Further explanation on UTC/Zulu time
It has normalized the iso date to a zulu date (zero offset iso date). It is still the same datetime, but it has converted the timezone offset into hours making the timezone offset zero.
date [2013-05-09]
separator [T]
time [00:00:00]
offset [-04:00]
The fundamental aspect is that 00:00:00.000-04:00 is the same than 04:00:00.000Z.
If you're simply trying to display the date as someone living in that time would have remembered it (in your case, October 13th happened on October 13th), you may be able to (ab)use Moment Timezone, which appears to format the date as expected:
moment.tz("1932-10-13T00:00:00-04:00", "America/Toronto").tz("UTC").format(); // 1932-10-13T04:00:00Z
In your case, this hacktechnique results in 1932-10-13T04:00:00Z which may be what you are looking for.

Comparing 2 dates with momentJS

I am trying to compare a DAY/TIME e.g. Monday 09:00:00 with the current time to see if I am past that point in the week. e.g. If it is now 05:00:00 on Monday it should return true however it is returning false everytime
var dayTime = Moment("Wednesday 17:00:00", "dddd HH:mm:ss");
var now = Moment(Moment.now(), "dddd HH:mm:ss");
console.log(Moment.utc(dayTime).isBefore(now)); //returns false all the time
I found the following similar questions but it didn't seem to fix the issue after formatting the time.
Comparing two times with Moment JS
When I replace the moment.now() with a string such as "Wednesday 17:00:00" it returns the expected result.
Any idea what I need to do to moment.now() in order for this to work correctly?
Moment.now can be used as an extension point, but it's really not a public API. To get the current time in momentjs you just call moment(). Note that all moment calls use lowercase moment.
To see if your date and time is before the current time, you would just call:
moment('01/01/2016', 'MM/DD/YYYY').isBefore(moment())
You would replace the date and format in question with your own.
I see that you have a date format that includes only day of week and time. Moment will parse this, but be aware that the behavior might not be what you expect. When I parse your date, I get Wednesday December 30, 2015. Exactly what day this lands on will vary by locale. In any case, I doubt that it is what you want. If at all possible, I would get year, month, and day.
If you would like to instead set the moment to Wednesday this week, set the day on the moment using .day(). For instance:
moment().day(3).format()
"2016-06-15T20:19:55-05:00"
For anyone who is interested, the code I posted in my question was changing the day/hour but was setting the year to 2015 which meant that it was always in the past.
To fix I separated out the Day and the Hour and set to moment. Then compared that with now. e.g.
moment().set({"Day": "Friday", "Hour": "17"}).isBefore(moment())

Having troubles with converting time in iso using java

I use the below code to format date time in iso format using java (I'm reducing 1 min from current time) and get the output as this "2016-03-17T11:38:21.xxxZ" < x represent some numbers> i want this to compare with the time which have mentioned in the DB.
Person who build that data insert query, he used javascript to get the time and format it in iso.
Date inside the DB is looks like this "2016-03-17T06:09:21.530Z" and its actual time is "11:39:21 GMT+0530 (India Standard Time)" which is similar to my current time but I'm comparing these two dates as string. and get 1min early data from DB.In that case i can't get an out put because as strings these two aren't match. can anybody recomand a solusion ?
I use OrientDB
Java Code
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
Calendar date = Calendar.getInstance();
long t = date.getTimeInMillis();
date.setTimeInMillis(t);
date.set(Calendar.MINUTE, date.get(Calendar.MINUTE) - 1);
String time1minEarly = df.format(date.getTime());
Using Calendar.set() and Calendar.get() does not modify the date in a way you intend:
This will modify the minutes field in your case. So subtracting "1" will reduce the minute but not give a viable date for cases where minute initially is zero.
You may just subtract a minutes of milliseconds from your "t" variable to get a true minute offset.
And for ease of use you might also consider following advise from #Prashant and using LocalDateTime class from joda library.
Thanks Everybody for your support.
I figure out How to do this. it's pretty easy. Both #rpy and #Prashant are correct. Calendar is not suitable for solve my issue. Also LocalDateTime too. but it did help me to figure out the correct way.
#rpy and #Prashant they both did miss one thing that the javascript time represent the UTC time. that's the issue. (it's 5.5 hours behind compared to my location) so, I figure out this below code. it did what i wanted to do.
It's pretty easy. all you have to do is provide your zone id.
(You can get Zone id using this code : go to the link - http://www.javadb.com/list-possible-timezones-or-zoneids-in-java/)
Also you can choose so many formats by changing "DateTimeFormatter" value.
ZoneId UTCzoneId = ZoneId.of("UTC");
ZonedDateTime time1minEarly = ZonedDateTime.now(UTCzoneId).minusMinutes(1);
String UTCtime1minerly = time1minEarly.format(DateTimeFormatter.ISO_INSTANT);
Out put is similar to this : "2016-03-17T10:39:21.530Z"
(- UTC time at that time : 2016-03-17T10:40:21.530Z)

parsing a UTC ISO date to a local time date in javascript/jquery

I have tried to search for the answer already, and although I find answers that are very similar, I don't think they are exactly what I am looking for. Please forgive me if this is already answered elsewhere.
I am trying to parse an ISO date in javascript so that I can compare it to the client system date and display information depending on if the ISO date is before or after the client system date.
This was fine until I needed to support IE8 and now I am stuck.
I have created a function because I have three different dates that I need to do this to.
for example, my ISO date is: 2015-12-22T11:59 in UTC time.
but once my date is parsed, the full date is 11:59 in local time, no matter which time zone i test, it's always 11.59 in THAT time zone.
I know that the function I have created currently doesn't do anything with timezone, this is where I am stuck. I don't know what to add to get my end date to change as a reflection of the timezone of the clients machine.
any help or advice would be greatly appreciated.
I am not able to use something like moments.js because I have an upload restriction.
Jquery is available though. or plain javascript.
<script>
function setSaleContent() {
//creating a new date object that takes the clients current system time. so we can compare it to the dates stored in our array
var currentDate = new Date();
console.log(currentDate + " this is the clients date ");
//These variables actually come from an external array object, but I'm putting them in here like this for this example.
var destinations = {
freedate: "2015-12-16T11:59",
courierdate: "2015-12-22T11:59",
nextdaydate: "2015-12-23T11:59",
}
//fetch all the ISO dates from the array.
var freeDateISO = destinations["freedate"];
var courierDateISO = destinations["courierdate"];
var nextdayDateISO = destinations["nextdaydate"];
//I am creating this reusable function to split up my ISO date for the sake of IE8.. and create it into a date format that can be compared against another date. I know that this isn't doing anything with my timezone and that is where my problem lies.
function parseDate(str) {
var parts = /^(\d{4}).(\d{2}).(\d{2}).(\d{2}):(\d{2})/.exec(str);
if (parts) {
return new Date(parts[1], parts[2] - 1, parts[3], parts[4], parts[5]);
}
return new Date();
}
//I would like this date to change to reflect the time zone of the clients system time.
//currently returns the date at 11.59 regardless of timezone.
//If i was in GMT i would want it to say 11.59
//If i was in CT time I would like this to say 05.59
//If i was in Perth I would like this to say 19:59
var freeDate = parseDate(freeDateISO);
console.log(freeDate + " this is the converted date for IE")
}
window.onload = setSaleContent;
The simple solution is to append Z to the ISO date to indicate it is in UTC time, such as 2015-12-22T11:59Z.
When JavaScript parses that date as a string, it will then automatically convert the UTC date to the local time zone.
While this is simple enough with a parsing call in the form new Date(str);, it will not play nice with your parse call with numerical arguments targeting IE8 and other old browsers.
A polyfill for parsing ISO dates with timezone exists: Javascript JSON Date parse in IE7/IE8 returns NaN
This can replace your custom parseDate function after some modification to take an input string.
Alternatively, implement your own custom date manipulater to account for the local timezone using the .getTimezoneOffset() method on the newly created date, which gives the time zone offset in minutes, but you will have to come up with a method of utilising the offset such as adjusting hours and minutes, due to the limited methods of the JavaScript date object.

how to get current date in the below format using jquery

how to display the date in this below format using jQuery.
Thursday, January 08, 2013
I saw some plugins but wondering if there is a way without using any plugin.
Please advise if there is a straightforward answer using JavaScript, that's fine too.
The simplest answer is to use:
date.toLocaleDateString()
But, it will use the locale defined by the user's system. The American/English locale fitting your desired output. (I'm not sure about other locales and how they format dates).
So, if you want the date string to always be in that format, this will not be the best answer for you. But, if you want the date to match the user's locale, this answer is the simplest and most correct. :)
http://jsfiddle.net/SyjpS/
var date = new Date();
console.log(date.toLocaleDateString()); // Tuesday, January 08, 2013 (on my machine)
EDIT — If you're asking how to change the calendar so that today is Thursday instead of Tuesday, you may need to talk to Caesar about adjusting the calendar realignment. For this, you'll need a time machine. I suggest that you seek out the Doctor, but he may not be willing to change history willy nilly.
Here's a quick/simple example of what you're asking for:
EDIT - I've update the code for reuse and include the day 0 padding change.
var d = new Date();
console.log(formatDate(d));
function formatDate(d){
var months = ["Januaray", "February", "March"]; //you would need to include the rest
var days = ["Sunday", "Monday", "Tuesday"];//you would need to include the rest
return days[d.getDay()] + ", " + months[d.getMonth()] + " " + (d.getDate() < 10 ? "0" + d.getDate() : d.getDate()) + ", " + d.getFullYear();
}
Output for today: Tuesday, Januaray 08, 2013
EXAMPLE
Simply use DateJS not to reinvent the wheel.
You may read the API documentation here:
http://code.google.com/p/datejs/wiki/APIDocumentation
The date methods allow you to retrieve all of the different parts of the date and time as numerical values. In the case of the month of the year and the day of the week, the number that is provided is one less than you would normally expect. The reason for this is that the most common use for these values is to use it to look up the name of the month or day from an array and as arrays in JavaScript are numbered from zero, providing the numbers like that reduces the amount of code needed to do the name lookups.
We can go one better than just doing this lookup using the retrieved values though. What we can do is to add extra methods to the Date object to allow us to retrieve the month and day names whenever we want the exact same way that we retrieve any of the other information about the date.
The probable reason why the following methods are not built into the JavaScript language itself is that they are language dependent and need to have different values substituted into the code depending on the language that you want to display the month and day in. For the purpose of showing you how to code this I am going to use the Emglish names for the months and days. If you want to display dates in a different language you will need to substitute the names from that language for their English equivalents.
What we are going to do is to add getMonthName() and getDayName() methods to all our dates so that we can get the month name or day name by calling these new methods directly instead of having to call getMonth() or getDay() and then do an array lookup of the corresponding name. What we are actually doing is building the required array lookups into the new methods so that we can automatically get the correct names for any of our date objects simply by calling the appropriate method.
We don't neeed all that much code to do this. All you need to do to add the getMonthName() and getDayName() methods to all of the date objects that you use is to add the following short piece of code to the very top of the javaScript code attached to the head of your page. Any subsequent processing of date objects will then be able to use these methods.
Date.prototype.getMonthName = function() {
var m = ['January','February','March','April','May','June','July',
'August','September','October','November','December'];
return m[this.getMonth()];
}
Date.prototype.getDayName = function() {
var d = ['Sunday','Monday','Tuesday','Wednesday',
'Thursday','Friday','Saturday'];
return d[this.getDay()];
}
So now with that in place we can display today's date on the page using those new methods in addition to the existing ones. For example we might use the following to get the full date and display it using an alert:
var today = new Date;
alert((today.getDayName() + ', ' + today.getDate() + ' ' + today.getMonthName() + ', ' + today.getFullYear());
Alternatively, we can just retrieve the current month June and day of the week Sunday and use them however we want just the same as for any of the other parts of the date.
function disp() {
var today = new Date;
document.getElementById('mth').innerHTML = today.getMonthName();
document.getElementById('dow').innerHTML = today.getDayName();
}

Categories