I am just printing the ISO datetime with timezone as per the below documentation
http://support.sas.com/documentation/cdl/en/lrdict/64316/HTML/default/viewer.htm#a003169814.htm
This is my code
TimeZone tz = TimeZone.getTimeZone("UTC");
DateFormat df = new SimpleDateFormat("yyyy-mm-dd'T'hh:mm:ss.nnnnnn+|-hh:mm");
df.setTimeZone(tz);
dateTimeWithTimeZone = df.format(new Date());
However i am getting this exception
Illegal pattern character 'n'
I cant use this format directly in Java ?
java.time
dateTimeWithTimeZone = Instant.now().toString();
System.out.println(dateTimeWithTimeZone);
When I ran this snippet just now, I got this output:
2019-03-18T22:28:13.549319Z
It’s not clear from the page you link to, but it’s an ISO 8601 string in UTC, so should be all that you need. I am taking advantage of the fact that the classes of java.time produce ISO 8601 output from their toString methods. The linked page does show the format with hyphens, T and colons (2008-09-15T15:53:00+05:00), it shows another example with decimals on the seconds (15:53:00.322348) and a third one with Z meaning UTC (20080915T155300Z), so I would expect that the combination of all three of these would be OK too.
The format you used in the quesiton seems to try to get the offset as +00:00 rather than Z. If this is a requirement, it’s only a little bit more complicated. We are using an explicit formatter to control the variations within ISO 8601:
DateTimeFormatter iso8601Formatter
= DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSSSSxxx");
dateTimeWithTimeZone = OffsetDateTime.now(ZoneOffset.UTC).format(iso8601Formatter);
System.out.println(dateTimeWithTimeZone);
2019-03-18T22:28:13.729711+00:00
What went wrong in your code?
You tried to use the formatting symbols from your source with SimpleDateFormat. First, you should never, and especially not in Java 8 or later, want to use SimpleDateFormat. That class is notoriously troublesome and long outdated. Second, some of its format pattern letters agree with the symbols from your source, some of them don’t, so you cannot just use the symvol string from there. Instead you need to read the documentation and find the correct format pattern letters to use for year, month, etc. And be aware that they are case sensitive: MM and mm are different.
Link
Oracle Tutorial: Date Time
explaining how to use java.time.
I'm using a JavaScript datepicker that gives me the selected date based on the language. So when the language is Dutch I get an output like 21-09-2017 (dd-mm-yyyy) And for English 21/09/2017.
When I want to cast these Strings to Dates (CDate) I get a problem with the format. Day = Month or Month = Day. What is the best way to make a Date from a string based on the format used in the string?
A solution would be to write a function for each specific culture to handle the dates but i'm guessing there is a default function in .Net??
You can use DateTime.ParseExact to get what you want as shown here.
You can provide the format like so:
dateString = "15/06/2008 08:30" //Your Date time
format = "g" //General Fromat
provider = New CultureInfo("fr-FR") //French
result = Date.ParseExact(dateString, format, provider) //Parsed Result
this will result in: 6/15/2008 8:30:00 AM
This or course only works if you know the culture. Also you may want to check out the Date Time Format Strings found here.
Convert.ToDateTime(String).ToString("dd-MM-yyyy")
OR
DateTime.ParseExact(String, "dd/MM/yyyy", CultureInfo.InvariantCulture)
I would like to format this kind of number:
1234567.99 (obviously all thousands digits are optional)
In this way: 1.234.567,99
I know it is possible with Eval, but I didn't find an useful guide to do this.
Could you help me?
Thanks
There is an overload of Eval that takes three parameters (the link also contains a sample):
Container
Expression
Format
For the format, you'd specify "{0:c}" or whatever format you like. For a list of the Standard Numeric Format Strings, see this link. If you want to specify your format with a custom format string, e.g. use "{0:#,##0.00}".
You can use the ToString() extension
var value = 1234567.99;
Console.WriteLine(value.ToString("C3", CultureInfo.CurrentCulture));
Or by stating your culture
Console.WriteLine(value.ToString("C3", CultureInfo.CreateSpecificCulture("sv-SE")));
I am having trouble to implement "simple" parsing of a date. The requirement is to allow enter year in two or four digits. When two digits are entered then make the split date for deciding into what century it belongs the first of January next year. Here is what I have so far:
DateTime now = new DateTime();
int pivotYear = now.getYear() - 49; // 2013 - 49 = 1964 where 49 is the
DateTimeParser[] parsers = {
DateTimeFormat.forPattern("dd/MM/yy").withPivotYear(pivotYear).withLocale(new Locale("en", "NZ")).getParser(),
DateTimeFormat.forPattern("dd/MM/yyyy").withLocale(new Locale("en", "NZ")).getParser()
};
DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, parsers).toFormatter();
DateMidnight birthDate = new DateMidnight(formatter.parseDateTime(dateOfBirth));
Unfortunatelly it is not doing what I would expect. Let's say for today's date (11/04/2013) and dateOfBirth = "01/01/14" it returns 2014-01-01T00:00:00.000+13:00. The expected result would be 1914-01-01T00:00:00.000+13:00
When I look at the JavaDoc for the append method I see this sentence
The printer and parser interfaces are the low-level part of the
formatting API. Normally, instances are extracted from another
formatter. Note however that any formatter specific information, such
as the locale, time-zone, chronology, offset parsing or pivot/default
year, will not be extracted by this method.
So I have decided to move the Pivot stuff into the DateTimeFormatterBuilder class so now the code looks like this:
DateTimeParser[] parsers = {
DateTimeFormat.forPattern("dd/MM/yy").getParser(),
DateTimeFormat.forPattern("dd/MM/yyyy").getParser()
};
DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, parsers).appendTwoDigitYear(pivotYear).toFormatter().withLocale(new Locale("en", "NZ"));
Unfortunatelly this is not sorting the issue. On contrary it is failing this time on
java.lang.IllegalArgumentException: Invalid format: "01/01/14" is too short
at org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:866)
from the same javadoc I get this sentence
Appends a printer and a set of matching parsers. When parsing, the first parser in the list is selected for parsing. If it fails, the next is chosen, and so on. If none of these parsers succeeds, then the failed position of the parser that made the greatest progress is returned.
Based on this the first parser should have pick up the job but it looks like the second one is triggered and it fails because it expects longer year.
Any help would be deeply appreciated.
Cheers
Tomas
So it looks like no one is interested enough to answer so I had to figure it by myself :-).
I should be scrolling a bit down in the JavaDoc and I should have the answer in no time. There is another appendTwoDigitYear method which will do the job I am after.
So here is the code I am using right now
DateTimeFormatter formatter = new DateTimeFormatterBuilder().appendDayOfMonth(1).appendLiteral("/").appendMonthOfYear(1).appendLiteral("/").appendTwoDigitYear(pivotYear, true).toFormatter().withLocale(new Locale("en", "NZ"));
DateMidnight birthDate = new DateMidnight(formatter.parseDateTime(dateOfBirth));
Hope it will help someone in the future.
Cheers
Tomas
I am not expert in writing regular expressions so need your help. I want to validate date in "dd-MMM-yyyy" format i.e. 07-Jun-2012. I am using RegularExpressionValidator in asp.net.
Can anybody help me out providing the expression?
Thanks for sharing your time.
Using a DatePicker is probably the best approach. However, since that's not what you asked, here's an option (although it's case sensitive):
^(([0-9])|([0-2][0-9])|([3][0-1]))\-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\-\d{4}$
In addition, here's a place you can easily test Regular Expressions: http://www.regular-expressions.info/javascriptexample.html
Regex without leading zero in day.
^\d{1,2}-[a-zA-Z]{3}-\d{4}$
Update Regex with leading zero in day.
^\d{2}-[a-zA-Z]{3}-\d{4}$
It's not regex, but you can use build in DateTime.TryParseExact function to validate your datetime string
DateTime dateTime;
string toValidate = "01-Feb-2000";
bool isStringValid = DateTime.TryParseExact(
toValidate,
"dd-MMM-yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dateTime);
The accepted solution allows '00' as the day, so here is a fix for that:
^(([1-9])|([0][1-9])|([1-2][0-9])|([3][0-1]))\-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\-\d{4}$
Notes/Exceptions:
1.Be aware of case sensitivity issues. Eg. 'DEC' will not pass while 'Dec' will pass. You may want to convert the regex string and test string to lowercase before testing (if your application allows).
2.This will not catch days that don't exist, like Feb 30th, June 31st, etc.
"\d{4}\d{2}\d{2}|\d{2}/\d{2}/\d{4}|\d{2}.\d{2}.\d{4}|\d{2}\-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)|(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\d{2}\-\d{4}|\d{4}-\d{2}-\d{2}"
These format is mm.dd.yyyy, d-MMM, mm.dd.yyyy
Yet another idea would be to try this (similar to user1441894's idea):
var x = DateTime.Parse("30-Feb").GetDateTimeFormats();
I learned to use this yesterday (for a different purpose). So try-catch this statement to deal with validity/invalidity of the date :)
"^(([1-9]|0[1-9]|1[0-9]|2[1-9]|3[0-1])[-]([JAN|FEB|MAR|APR|MAY|JUN|JULY|AUG|SEP|OCT|NOV|DEC])[-](d{4}))$"
using System.Text.RegularExpressions
private void fnValidateDateFormat(string strStartDate,string strEndDate)
{
Regex regexDt = new Regex("(^(((([1-9])|([0][1-9])|([1-2][0-9])|(30))\\-([A,a][P,p][R,r]|[J,j][U,u][N,n]|[S,s][E,e][P,p]|[N,n][O,o][V,v]))|((([1-9])|([0][1-9])|([1-2][0-9])|([3][0-1]))\\-([J,j][A,a][N,n]|[M,m][A,a][R,r]|[M,m][A,a][Y,y]|[J,j][U,u][L,l]|[A,a][U,u][G,g]|[O,o][C,c][T,t]|[D,d][E,e][C,c])))\\-[0-9]{4}$)|(^(([1-9])|([0][1-9])|([1][0-9])|([2][0-8]))\\-([F,f][E,e][B,b])\\-[0-9]{2}(([02468][1235679])|([13579][01345789]))$)|(^(([1-9])|([0][1-9])|([1][0-9])|([2][0-9]))\\-([F,f][E,e][B,b])\\-[0-9]{2}(([02468][048])|([13579][26]))$)");
Match mtStartDt = Regex.Match(strStartDate,regexDt.ToString());
Match mtEndDt = Regex.Match(strEndDate,regexDt.ToString());
if (mtStartDt.Success && mtEndDt.Success)
{
//piece of code
}
}