Parsing time string in java 8 - Invalid value for ClockHourOfAmPm [duplicate] - datetime

This question already has answers here:
How to set 24-hours format for date on java?
(10 answers)
Closed 3 years ago.
I am trying to convert time zones with given time in my properties file.
package test1;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class TimeZoneConversion {
private static final String DATE_FORMAT = "yyyy-MM-dd-hh-mm-ss";
public static void main(String[] args) {
String ds = "2019-03-18 13-14-48";
LocalDateTime ldt = LocalDateTime.parse(ds, DateTimeFormatter.ofPattern(DATE_FORMAT));
System.out.println("ldt : "+ldt);
ZoneId singaporeZoneId = ZoneId.of("Asia/Singapore");
System.out.println("TimeZone : " + singaporeZoneId);
//LocalDateTime + ZoneId = ZonedDateTime
ZonedDateTime asiaZonedDateTime = ldt.atZone(singaporeZoneId);
System.out.println("Date (Singapore) : " + asiaZonedDateTime);
ZoneId newYokZoneId = ZoneId.of("America/New_York");
System.out.println("TimeZone : " + newYokZoneId);
ZonedDateTime nyDateTime = asiaZonedDateTime.withZoneSameInstant(newYokZoneId);
System.out.println("Date (New York) : " + nyDateTime);
DateTimeFormatter format = DateTimeFormatter.ofPattern(DATE_FORMAT);
System.out.println("\n---DateTimeFormatter---");
System.out.println("Date (Singapore) : " + format.format(asiaZonedDateTime));
System.out.println("Date (New York) : " + format.format(nyDateTime));
}
}
SO I am getting error :
Exception in thread "main" java.time.format.DateTimeParseException: Text '2019-03-18 13-14-48' could not be parsed: Invalid value for ClockHourOfAmPm (valid values 1 - 12): 13
at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1855)
at java.time.LocalDateTime.parse(LocalDateTime.java:492)
at test1.FirstClass.main(FirstClass.java:20)
I do not have AM/PM value in the date time that I getting from properties file. This value is stored in String ds. in the above code I have hardcoded it. How does it work? How to make it work with the time date format which I have given?

You should change the DATE_FORMAT to:
private static final String DATE_FORMAT = "yyyy-MM-dd HH-mm-ss";
If you refer the DateTimeFormatter docs you see the description as follows:
H hour-of-day (0-23)
In your case you are supplying the hour as the hour-of-day (HH) instead of in clock-hour-of-am-pm (hh a) format from your properties file. And as 13 ( > 12) is not an acceptable value for clock-hour-of-am-pm without the AM/PM you are getting an exception.
If you want it in clock-hour-of-am-pm you need to change the format to:
private static final String DATE_FORMAT = "yyyy-MM-dd hh-mm-ss a";
And also add the AM/PM information in the date string:
String ds = "2019-03-18 12-14-48 AM";

Related

Flutter DateTime parsing

I want to add offset GMT +05:30 to Time but I don't know how to do that
String offset = data ['utc_offset'].substring(1,);
ntime =ntime.add(Duration(hours:int.parse(offset)));
Since there is " : " in the middle of 05:30 I can't add the exact value..
PS: I'm using http://worldtimeapi.org JSON API
You can parse the offset time by using a RegExp. I have used named groups in my example since I finds it more simple to understand what each part of the regexp are extracting:
import 'dart:io';
void main() {
const offset = '+01:00';
final regexp =
RegExp(r'^(?<plusMinus>[+-]?)(?<hours>[\d]+):(?<minutes>[\d]+)');
final match = regexp.firstMatch(offset);
print(match.namedGroup('plusMinus'));
print(match.namedGroup('hours'));
print(match.namedGroup('minutes'));
final offsetDuration = Duration(
hours: int.parse(match.namedGroup('hours')),
minutes: int.parse(match.namedGroup('minutes')));
DateTime time;
if (match.namedGroup('plusMinus') == '+') {
time = DateTime.now().add(offsetDuration);
} else if (match.namedGroup('plusMinus') == '-') {
time = DateTime.now().subtract(offsetDuration);
} else {
time = DateTime.now();
}
print(time);
}

Parse string to DateTime in Flutter (Dart) [duplicate]

This question already has answers here:
How do I convert a date/time string to a DateTime object in Dart?
(8 answers)
Closed 1 year ago.
I am trying to parse String formatted like "23.1.2020" to DateTime object, but nothing works for me. I tried to use some packages like intl or date_format, but none of these can do the job.
DateTime todayDate = DateTime.parse("12.04.2020");
formatDate(todayDate, [yyyy, '/', mm, '/', dd, ' ', hh, ':', nn, ':', ss, ' ', am])
Do you have any idea, how to parse this?
Ok, I found way how to do that:
import 'package:intl/intl.dart';
DateFormat format = DateFormat("dd.MM.yyyy");
print(format.parse(date));
If you are absolutely sure that your date format will always be "dd.MM.yyyy" you could do this :
DateTime todayDate = DateTime.parse("12.04.2020".split('.').reversed.join());
This trick will format your date to "yyyyMMdd" format, which, according to the docs, is accepted by DateTime.parse().
Try out this package, Jiffy, it also runs on top of Intl, but makes it easier using momentjs syntax. See below
var date = Jiffy("12.04.2020", "dd.MM.yyyy").format("dd, Oct yy"); // 12, Apr 20
You can also do the following default formats
var date = Jiffy("12.04.2020", "dd.MM.yyyy").yMMMMd; // April 12, 2020
Hope this helps
Fuction Convert date to string :
String dateTostring(DateTime datevalue)
{
String _stringdate ="";
_stringdate = datevalue.month.toString()+"."+datevalue.day.toString()+"."+datevalue.year.toString() ;
return _stringdate;
}
Then fuction convert string to date:
DateTime dateStringtodate(String stringdate)
{
DateTime _stringdate;
List<String> validadeSplit = stringdate.split('.');
if(validadeSplit.length > 1)
{
int day = int.parse(validadeSplit[1].toString()));
int month = int.parse(validadeSplit[0].toString());
int year = int.parse(validadeSplit[2].toString());
_stringdate = DateTime.utc(year, day, month);
}
return _stringdate;
}

datetime parsing from excel sheet in asp.net

i want to get a datetime value from excel sheet and take the highest and the lowest date
i read the excel sheet and put it in datatable :
i tried this code :
protected void CheckTheFP(DataTable data)
{
if (data.Rows.Count != 0)
{
DateTime ds = new DateTime();
err.Text = DateTime.TryParseExact(data.Rows[0][2].ToString(), "MM/dd/yy hh:mm tt",
CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out ds) + "" ;
}
}
but i always get false ... don't know why ?
and is there a way to sort this datatable or take the highest and lowest date
this the excel sheet i read from
This format string should work: "M/dd/yy h:mm tt". I've used single M because the month has one digit, the same applies to the hours. I've used CultureInfo.InvariantCulture to prevent that all / will be replaced with your actual date-separator (in case that it's different).
You can use LINQ:
var allDateTimes = data.AsEnumerable()
.Select(row => DateTime.ParseExact(row.Field<string>("Time"), "M/dd/yy h:mm tt", CultureInfo.InvariantCulture));
DateTime min = allDateTimes.Min();
DateTime max = allDateTimes.Max();
If you want to be on the safe side you should use TryParseExact, for example with this code:
IEnumerable<DateTime> allDateTimes = data.AsEnumerable()
.Select(row => {
string time = row.Field<string>("Time").Trim();
DateTime dt;
if (DateTime.TryParseExact(time, "M/dd/yy h:mm tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
return (DateTime?) dt;
return null; // set a breakpoint here to see which value could not be parsed
})
.Where(dt => dt.HasValue)
.Select(dt => dt.Value);
DateTime min = allDateTimes.Min();
DateTime max = allDateTimes.Max();
Edit: you: "when i try to use it on the date 11/2/14 4:42 PM you see the 11 is not in M datetime format
The month is not the problem. Use single d instead because the days can have a single digit also.
So: "M/d/yy h:mm tt"

How to convert date string to specific date format?

I get date string value(3/13/2013 12:00:00AM) from database and i need to convert like this format (yyyy-mm-dd). Please help me solve this.
string targetdate = "3/13/2013 12:00:00AM";(getting date value from DB)
DateTime lastdate = DateTime.ParseExact(targetdate, "yyyy-mm-dd",
System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat);
And I tried
Iformatprovider = null.
but i getting same error "String was not recognized as a valid DateTime"
I think the problem is with the date time
"3/13/2013 12:00:00AM"
It should not be 12:00:00AM.
It should be 12:00:00PM.
Example
string targetdate = "3/13/2013 11:59:59AM";
DateTime lastdate = DateTime.ParseExact(targetdate,
"M/d/yyyy HH:mm:sstt",
System.Globalization.CultureInfo.InvariantCulture);
lastdate=lastdate.AddSeconds(1);
You will get
3/13/2013 12:00:00 AM
I would suggest you to cast it in the database end.
If you are using sql server then
Example
The following script uses the CONVERT() function to display different formats. We will use the GETDATE() function to get the current date/time:
CONVERT(VARCHAR(19),GETDATE())
CONVERT(VARCHAR(10),GETDATE(),10)
CONVERT(VARCHAR(10),GETDATE(),110)
CONVERT(VARCHAR(11),GETDATE(),6)
CONVERT(VARCHAR(11),GETDATE(),106)
CONVERT(VARCHAR(24),GETDATE(),113)
The result would look something like this:
Nov 04 2011 11:45 PM
11-04-11
11-04-2011
04 Nov 11
04 Nov 2011
04 Nov 2011 11:45:34:243
First you need to convert your date string to DateTime type object using the format "M/d/yyyy HH:mm:sstt" later you can get the formatted string using "yyyy-MM-dd". (You used lower case m for month, it should be upper case M for month.
string targetdate = "3/13/2013 12:00:00AM";
DateTime lastdate = DateTime.ParseExact(targetdate,
"M/d/yyyy hh:mm:sstt",
System.Globalization.CultureInfo.InvariantCulture);
string newFormat = lastdate.ToString("yyyy-MM-dd");
newFormat would contain "2013-03-13"
DateTime conversion is really easy in .Net if you know which datetime format you have and in which format you convert that.
Here is example for this.
String origionalDate = "12/20/2013"; // Format : MM/dd/yyyy
string origionalFormat = "MM/dd/yyyy";
string convertInToFormat="dd/MM/yyyy";
String convertedDate;
DateTime objDT;
if (DateTime.TryParseExact(origionalDate, origionalFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out objDT) == true)
{
convertedDate = objDT.ToString(convertInToFormat);
Response.Write("<b>Origional DateTime Format ( " + origionalFormat + " ) : </b>" + origionalDate);
Response.Write("<br/>");
Response.Write("<b>Converted DateTime Format ( " + convertInToFormat + " ) : </b>" + convertedDate);
}
else
{
Response.Write("<b>Not able to parse datetime.</b>");
}
For more details on this visit this link. Click Here...

Get difference in two different timestamps in Blackberry application

I would like to know how to calculate difference between two different timezones / timestamps in Blackberry application.
For e.g. Calculate difference in server timestamp and client timestamp
Please help.
Thanks.
Try this code:
class Scr extends MainScreen {
public Scr() {
String time1 = "2009-11-27 01:38:05";
String zone1 = "Pacific/Midway";
String time2 = "2008-05-01 12:38:05";
String zone2 = "MST";
long timeDiff = getTimeDifference(time1, zone1, time2, zone2);
Date date = new Date(timeDiff);
add(new LabelField(String.valueOf(date)));
}
public long getTimeDifference(String timestamp1, String timezone1,
String timestamp2, String timezone2) {
long time1 = getTime(timestamp1, TimeZone.getTimeZone(timezone1));
long time2 = getTime(timestamp2, TimeZone.getTimeZone(timezone2));
return time2 - time1;
}
public long getTime(String time, TimeZone timeZone) {
Date formatter = new Date(HttpDateParser.parse(time));
int offset = timeZone.getRawOffset();
return formatter.getTime() + offset;
}
}

Resources