Pergunta

I'm trying to get a decimal value for a value that is expressed in a date. My problem is that I need only the time in the date, not the actual date itself. So here part of my .json data:

var data = [
  {
    "Id":"1390794254991",
    "Tz":"Europe/Amsterdam",
    "From":"27. 01. 2014 4:44",
    "To":"27. 01. 2014 12:09",
    "Sched":"08. 02. 2014 5:24",
    "Hours":"7.430"
}]

So basically i would like to take the "From" value and get just the time returned in a decimal value. I don't think converting the time to a decimal number with Time Formatting, it's just the splitting of a value that seems pretty hard to me. Any of you guys have a clue how this could be achieved?

Thanks,

Cas

Edit: Okay, here we go. I made a JSFiddle to clear things up. Because there is a TIME (HH:MM) in my date, the rectangles in my barchart don't come on a specific day in the xAxis. INSTEAD they come out on a day AND time on the xAxis.

I just need it to be the specific date, not the date AND time.

I think I have to change something in the following part:

dataFiltered.forEach(function(d) {
         d.From = parseDate(d.From);
    });

Just don't really see what...

Foi útil?

Solução

With d3, you'd construct a time parser, give it a string to parse, and get back a Date object.

var parser = d3.time.format('%d. %m. %Y %H:%M');
var date = parser.parse("05. 52. 2014 4:32");

Then you can do as you wish with this date object, including

var hours = date.getHours() // 4
var minutes = date.getMinutes() // 32

But, did you mean you don't want to use d3 (despite your question being tagged with d3)? If so, you can also use RegExp:

var dateString = "05. 52. 2014 4:32";
var matches = dateString.match(/(\d?\d):(\d\d)$/);
// yields ["4:32", "4", "32"]

Then you can get the tokens you want either via

var hours = matches[1];
var minutes = matches[2]

or

var hours = RegExp.$1;
var minutes = RegExp.$2

In either case though, RegExp gives you back strings, so you need to convert them to Numbers if you're doing quantitative stuff with them:

var hours = parseInt(matches[1]);

or more cryptically

var hours = +matches[1];
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top