Date format in D3.js - d3.js

I have a column (date) in csv which stores the date in "2003-02-01"(y-m-d). I would like to format the date in month and year like Apr 2003. how do i do that?
var format = d3.time.format("%m-%Y");
data.forEach(function(d,i) {
d.date = format(d.date);
});
I am getting the following error Error: TypeError: n.getFullYear is not a function Line: 5
the csv file contains values:
200,300,400,288,123,2003-01-01
300,700,600,388,500,2003-02-01
what is the issue here?

Javascript doesn't automatically recognize the values in the CSV file as dates, just reading them in as strings. d3's time functions make it pretty easy to convert them to datetime objects:
> parseDate = d3.time.format("%Y-%m-%d").parse
> parseDate('2003-01-01')
Wed Jan 01 2003 00:00:00 GMT-0600 (Central Standard Time)
To format the dates like you want, we need to go the other way, from a date object to a string:
> formatDate = d3.time.format("%b-%Y")
> formatDate(parseDate('2003-01-01'))
"Jan-2003"
I would recommend representing your dates within your program with date objects and only formatting them as strings when you need to display them.

D3 version 4 has different time methods now.
https://keithpblog.org/post/upgrading-d3-from-v3-to-v4/
https://github.com/d3/d3/blob/master/CHANGES.md
Your source date
var d = {created_time : "2018-01-15T12:37:30+0000"}
The structure of that date = %Y-%m-%dT%H:%M:%S%Z
I search google with "2018-01-15T12:37:30+0000" and it's suggestions provided the date structure string. Handy.
Create a timeParser to convert(parse) your date string into a date object
var parseDate = d3.utcParse("%Y-%m-%dT%H:%M:%S%Z")
//parseDate(d.created_time)
Now create a time formatter to return a formated date string for displaying.
var formatDate = d3.timeFormat("%b-%Y")
return formatDate(parseDate(d.created_time))
i.e.
Jan-1970

from Adam answer, here is a small helper function to convert a time string from a format to another:
var formatTime = function(input, formatInput, formatOutput){
var dateParse = d3.time.format(formatInput).parse;
var dateFormat = d3.time.format(formatOutput);
return dateFormat(dateParse(input));
};
use:
formatTime("2003-01-01", "%Y-%m-%d", "%b-%Y");
// output -> "Jan-2003"

if you are getting date lets say in variable " d = (e.g: '2003-03-01')" in string format then,
var monthNameFormat = d3.time.format("%b-%Y");
return monthNameFormat(new Date(d));
this will result date in "Jan-2003" format.

In D3Js v3, this worked for me:
var s = "2018-11-01T19:37:55Z";
d3.time.format("%Y-%m-%dT%H:%M:%SZ").parse(s);
// Thu Nov 01 2018 19:37:55 GMT-0700 (Pacific Daylight Time)

Related

D3 time string convert to date

I'm new to D3.
I have a string stored in a var, below is the var.
var expense = {"name":"jim","amount":34,"date":"11/12/2015"};
and I want to only show the year of the date.
var parser = d3.timeParse("%Y");
expense.date = parser(expense.date);
console.log(expense);
but I am just getting null for the date. Anyone know how to fix this? I should get the result:
{name: "jim", amount: 34, date: 2015 }
If you want to use d3 date tools, first you have the parse your string to date format
const tParser = d3.timeParse("%d/%m/%Y")
then use on your string
const date = tParser(expense.date)
then use d3.timeFormat("%Y")
const year = d3.timeFormat("%Y")(date)
Or much simpler just split your string as rioV8 commented
expense.date = +expense.date.split('/')[2]
Thought it could be useful to know how to use d3 time format works, more info

Swift DateFormatter Extract Time

I've been trying to return a date with just Time. I tried DateFormatter, but will always retrieve a full date for some reason.
//Declare Date Formatter 1
let dateFormatter1 = DateFormatter()
dateFormatter1.dateFormat = "yyyy-MM-dd HH:mm:ss"
//Declare Date Formatter 2
let dateFormatter2 = DateFormatter()
dateFormatter2.dateFormat = "hh:mm"
//Retrieve date and set to proper date for DateFormatter
var date: Date = dateFormatter1.date(from: "2017-11-28 10:47:30")!
//Set String date to time format with dateFormatter2
let dateString = dateFormatter2.string(from: item)
//Reseting dateFormatter1 for to only use time (could be ambiguous)
dateFormatter1.dateFormat = "hh:mm"
//Set date to Date
date = dateFormatter1.date(from: dateString)!
print("String: \(dateString)")
print("Date: \(date)")
Output:
String: 10:47
Date: 2000-01-01 15:47:00 +0000
- timeIntervalSinceReferenceDate : -31565580.0
I want the Date: to be 10:47
Is this even possible?
No, it is not possible. The Variable date is of type Date which has full date information within it. When showing it in string format you can convert it as you want, but while storing in the variable of type Date it stores the full information.

java.time.format.DateTimeParseException: Text could not be parsed at index 3

I am using Java 8 to parse the the date and find difference between two dates.
Here is my snippet:
String date1 ="01-JAN-2017";
String date2 = "02-FEB-2017";
DateTimeFormatter df = DateTimeFormatter .ofPattern("DD-MMM-YYYY", en);
LocalDate d1 = LocalDate.parse(date1, df);
LocalDate d2 = LocalDate.parse(date2, df);
Long datediff = ChronoUnit.DAYS.between(d1,d2);
When I run I get the error:
java.time.format.DateTimeParseException: Text could not be parsed at index 3
First of all, check the javadoc. The uppercase D represents the day-of-year field (not the day-of-month as you want), and uppercase Y represents the week-based-year field (not the year as you want). The correct patterns are the lowercase letters d and y.
Also, you're using month names in uppercase letters (JAN and FEB), so your formatter must be case insensitive (the default behaviour is to accept only values like Jan and Feb). And these month names are English abbreviations, so you must also use English locale to make sure it parses the names correctly (using java.util.Locale class).
So, your formatter should be created like this:
DateTimeFormatter df = new DateTimeFormatterBuilder()
// case insensitive to parse JAN and FEB
.parseCaseInsensitive()
// add pattern
.appendPattern("dd-MMM-yyyy")
// create formatter (use English Locale to parse month names)
.toFormatter(Locale.ENGLISH);
This will make your code work (and datediff will be 32).
The following code works. The problem is you are using "JAN" instead of "Jan".
DateTimeFormatter does not recognize that it seems. and also change the pattern to
"d-MMM-yyyy".
String date1 ="01-Jan-2017";
String date2 = "02-Feb-2017";
DateTimeFormatter df = DateTimeFormatter.ofPattern("d-MMM-yyyy");
LocalDate d1 = LocalDate.parse(date1, df);
LocalDate d2 = LocalDate.parse(date2, df);
Long datediff = ChronoUnit.DAYS.between(d1,d2);
Source: https://www.mkyong.com/java8/java-8-how-to-convert-string-to-localdate/
// DateTimeFormatterBuilder provides custom way to create a
// formatter
// It is Case Insensitive, Nov , nov and NOV will be treated same
DateTimeFormatter f = new DateTimeFormatterBuilder().parseCaseInsensitive()
.append(DateTimeFormatter.ofPattern("yyyy-MMM-dd")).toFormatter();
try {
LocalDate datetime = LocalDate.parse("2019-DeC-22", f);
System.out.println(datetime); // 2019-12-22
} catch (DateTimeParseException e) {
// Exception handling message/mechanism/logging as per company standard
}
Maybe Someone is looking for this it will work with date Format like 3/24/2022 or 11/24/2022
DateTimeFormatter.ofPattern("M/dd/yyyy")
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/dd/yyyy");
formatter = formatter.withLocale( Locale.US ); // Locale specifies human language for translating, and cultural norms for lowercase/uppercase and abbreviations and such. Example: Locale.US or Locale.CANADA_FRENCH
LocalDate date = LocalDate.parse("3/24/2022", formatter);
System.out.println(date);
Maybe you can use this wildcard,
String d2arr[] = {
"2016-12-21",
"1/17/2016",
"1/3/2016",
"11/23/2016",
"OCT 20 2016",
"Oct 22 2016",
"Oct 23", // default year is 2016
"OCT 24", // default year is 2016
};
DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder()
.parseCaseInsensitive().parseLenient()
.parseDefaulting(ChronoField.YEAR_OF_ERA, 2016L)
.appendPattern("[yyyy-MM-dd]")
.appendPattern("[M/dd/yyyy]")
.appendPattern("[M/d/yyyy]")
.appendPattern("[MM/dd/yyyy]")
.appendPattern("[MMM dd yyyy]");
DateTimeFormatter formatter2 = builder.toFormatter(Locale.ENGLISH);
https://coderanch.com/t/677142/java/DateTimeParseException-Text-parsed-unparsed-textenter link description here
Try using DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-LLL-yyyy",Locale.ENGLISH);

Simple D3: turn a date object into an attractive string?

This should be easy!
I have a JavaScript Date object and I want to turn it into an attractive string, using D3's time functions.
var format = d3.time.format('%e %b').parse;
console.log('graph_x', graph_x, typeof graph_x, String(graph_x), format(String(graph_x)));
This gives me:
graph_x
Tue Dec 25 2012 08:26:10 GMT+0000 (GMT)
object
Tue Dec 25 2012 08:26:10 GMT+0000 (GMT)
null
How can I turn my Date object into a nice String, like "Tue 25"?
d3.time.format takes a date object and returns a string.
format.parse takes a string and returns a date time object.
From the docs:
var format = d3.time.format("%Y-%m-%d");
format.parse("2011-01-01"); // returns a Date
format(new Date(2011, 0, 1)); // returns a string
Since you already have a date object, you don't need to parse it:
var format = d3.time.format('%e %b')
console.log(format(graph_x))

How can I get the last date from a list of dates in the database then compare it with the current date?

I’m trying to retrieve dates from the database then use it to compare with current date. How can I get the last date from a list of dates in the database then compare it with the current date? Here’s what I’ve tried but I get a exception: “LINQ to Entities does not recognize the method 'System.DateTime Last…”
var manageDate= from d in db.Enrollments.Select(da=>da.Date) select d;
var manageAssgnDate = from asgn in db.Enrollments.Select(asgn => asgn.Date) select asgn;
List<DateTime> newDate = manageDate.ToList();
I normally use lambdas:
// This gets the max date in the table
var manageDate = db.Enrollments.Max(da => da.Date);
Is this what you were asking for ?
Found a work-around:
var stdAssgn= from sa in db.Assignments where sa.StudentId==currentId select sa.Date;
var dt = stdAssgn.ToList().Last ();
String a = dt.ToString();
and to convert to DateTime if needed...
DateTime b=Convert.ToDateTime(a);

Resources