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.
Related
I have a date coming from a device and I want to do the following in Java:
I want to parse this date "2021-05-27T18:47:07+0530" to yyyy-mm-dd HH:MM:SS
Get the Date's offset value so that I can get the timezone offset as +05:30 or whatever timezone it comes from.
For the first one I have done this and looks like it works, but any better smaller approach will be handy as well:
String date = "2021-05-27T18:47:07+0530";
String inputPattern = "yyyy-MM-dd'T'HH:mm:ss+SSSS";
String outputPattern = "yyyy-MM-dd HH:mm:ss";
LocalDateTime inputDate = null;
String outputDate = null;
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern(inputPattern, Locale.ENGLISH);
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern(outputPattern, Locale.ENGLISH);
inputDate = LocalDateTime.parse(date, inputFormatter);
outputDate = outputFormatter.format(inputDate);
System.out.println("inputDate: " + inputDate);
System.out.println("outputDate: " + outputDate);
The Ouput is:
inputDate: 2021-05-27T18:47:07.053
outputDate: 2021-05-27 18:47:07
I don't know how to get the offset value of timezone in this case.
There are many recommendations including using SimpleDateFormat and ZonedDateTime etc but should be the best answer for this considering the offset value can be dynamic i.e it can be +05:30,+09:00 etc.
Please help in this case.
Try it like this.
String dateTime = "2021-05-27T18:47:07+0530";
String inputPattern = "yyyy-MM-dd'T'HH:mm:ssZ";
String outputPattern = "yyyy-MM-dd HH:mm:ss";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ",
Locale.ENGLISH);
ZonedDateTime zdt = ZonedDateTime.parse(dateTime, dtf);
ZoneOffset tz = zdt.getOffset();
System.out.println(tz);
System.out.println(zdt.format(DateTimeFormatter.ofPattern(outputPattern,
Locale.ENGLISH)));
Prints
+05:30
2021-05-27 18:47:07
The zoned date time could also be reprinted using the same format by which it was originally parsed.
I'm working in a Xamarin.IOs project. I'm trying to convert a DateTime object into the following format "dd. MMM yyyy" under "nb_NO" locale which should return something like, Ex: "05. feb 2018".
I'm using the following code snippets to achieve this, (C#)
var now = DateTime.Now;
var format = "dd. MMM yyyy";
var formatter = new NSDateFormatter { DateFormat = format, Locale = new NSLocale("nb_NO"), TimeZone = NSTimeZone.SystemTimeZone };
var nsDate = DateTimeToNSDate(now);
var formattedDate = formatter.StringFor(nsDate);
But what I get for formattedDate is something like Ex: "05. feb. 2018". There is an extra dot (period) after the month as well.
What can I do to get rid of this unexpected extra dot after the month in "nb_NO" locale?
After a long research, I tried the following string format, "dd. LLL yyyy".
You have to use LLL instead of MMM to render the month.
This just solved me the issue.
You can find all the possible formats here!
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);
here i used the sort function for date and time,but it's only sort on date not time,i want sort based on both date and time:
private function dregdate_sortCompareFuction(itemA:Object, itemB:Object):int {
var dt1:Date = DateField.stringToDate(String(itemA.sbatchregdate),"DD/MM/YYYY");
var dt2:Date = DateField.stringToDate(String(itemB.sbatchregdate),"DD/MM/YYYY");
var dateA:Date = new Date(dt1);
var dateB:Date = new Date(dt2);
return ObjectUtil.dateCompare(dateA, dateB);}
kindly please share your knowledge.
thanks
As you can see by the format you're passing, DateField.stringToDate only cares about dates and not times.
You could use Date.parse if your input string was in one of these formats:
MM/DD/YYYY HH:MM:SS TZD
HH:MM:SS TZD Day Mon/DD/
Mon DD YYYY HH:MM:SS
Day Mon DD HH:MM:SS TZD YYYY
Day DD Mon HH:MM:SS TZD YYYY
Mon/DD/YYYY HH:MM:SS TZD
YYYY/MM/DD HH:MM:SS TZD
but yours is not.
So give this, i'd use a Regular Expression to extract the individual values from the string and then build the Date object manually, something like:
var regex:RegExp = /^(\d+)\/(\d+)\/(\d+) (\d+):(\d+)$/i;
var data:Object = regex.exec(itemA.sbatchregdate);
var dateA:Date = new Date(o[3], o[2]-1, o[1], o[4], o[5]);
once you have the two dates created with the proper time values, the comparison should work as expected.
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)