This question already exists:
Checking the validity of a date [duplicate]
Closed 6 years ago.
how to check whether the 30 or 31th day of a month does exist or not.
31.09.2016 doesn't exist but will be shown as 01.10.2016 in Java and Javascript. Even with the correct locales etc. Any solutions in javascript or java is welcome since an ajax request can solve this as well.
Thanks in advance
I think you should use the momentjs library for any kind of date manipulation in javascript: MomentJS
var date = moment('31.09.2016','DD.MM.YYYY');
console.log(date.isValid()); // This will print false in case of an invalid date
Edit: Created a plunker so you can try it out: plunker example
. Check the javascript console
The answer from #nagyf is pretty good for js, on the java side you should set the leninent property to false in the DateFormat and then you will get an ParseException if the date is invalid.
Example:
final String d = "31/09/2016";
final DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
df.setLenient(false);
final Date parsDate = df.parse(d);
System.out.println(d);
Here is solution for Java
try{
String date = "31/9/2016";
Data d = new Date();
DateFormat df = new SimpleDateFormat("đd/MM/yyyy");
df.setLenient(false);
d = df.parse(date);
catch(ParseException ex){
System.out.println("Invalid Date");
}
An alternative way of checking lastDay given vs what is actually on calendar would be if you are working with a valid date and a given lastDay : (not in javascript in groovy/java)
int day=31
Date givenDate = new Date()
Calendar cal = Calendar.instance
cal.setTime(givenDate)
int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH)
if (day > lastDay) {
// fail throw exception
}
//otherwise good to go
java.time
The YearMonth class is handy for this. This object can provide a LocalDate object representing the last day of the month. You can ask that object for its day-of-month number.
int numberOfLastDay =
YearMonth.of( 2016 , Month.SEPTEMBER )
.atEndOfMonth()
.getDayOfMonth() ;
Related
I am trying to pass a time stamp to my API that comes in the format of YYYY-MM-DD HH:MM:SS but i need to manipulate the time to add 5 hours.
Have I done something wrong here? Do I need to convert it to a JavaScript date first?
var manDate = "2020-08-16 16:15:00"
manDate.setHours(manDate.getHours() + 5);
data.manDate = manDate
console.log(manDate)
Expected output - 2020-08-16 21:15:00
When you create a var for date, you need to add the 'new Date()' method.
var manDate = new Date("2020-08-16 16:15:00");
manDate.setHours(manDate.getHours() + 5);
console.log(manDate.getHours());
And to log the hours use getHour() again in the log statement.
Use simpleDateFormat to format the date, then cast the formatted date to calendar and add hours to it.
Try with below code.
SimpleDateFormat sdfObj = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
sdfObj.parse("2020-08-16 16:15:00");
Calendar calendar = sdfObj.getCalendar();
calendar.add(Calendar.HOUR_OF_DAY, 5);
The question was asked to give a solution in java earlier. Below is the answer as per java.
Date newDate = DateUtils.addHours(oldDate, 5);
This question already has answers here:
Convert dd-mm-yyyy string to date
(15 answers)
Why does Date.parse give incorrect results?
(11 answers)
Closed 4 years ago.
I have this
let d = new Date("03-08-2018"); //dd-mm-yyyy
console.log(d.getMonth()); // returns 02, I want 07
I have my date in dd-mm-yy. The getMonth() thinks I'm using mm-dd-yy.
How do I get correct month and date.
Your date format is not standard, and I strongly recommend not to use such code on a client web code, because how it behaves would be client-dependent.
EDIT (thx RobG) : Don't use the builtin parser new Date(), this will get you into trouble depending on the client timezone, even if you use a proper format where the month seems to be correctly recognized.
You'll have to create some function to parse the string yourself and create a Date object with year, month and day manually set, that would be the safe way.
Example of manual parsing :
let regex = /^(\d{2})-(\d{2})-(\d{4})$/; // each parsing group is day-month-year
let date = '03-05-2018';
let match = regex.exec(date);
let month = +match[2] - 1; // starting at 0, remove -1 if you want 1-based month number
console.log(month); // returns 4 in this example '03-05-2018'
(of course you should also put some guards if the string is not matching the correct format)
JS Date give the month starts with 0. So Try this below for getting month from date
let d = new Date("03-05-2018"); //dd-mm-yyyy
console.log(d.getMonth()+1);
if you want 4, then you should add +2 ( but i am not sure why you want 4)
let d = new Date("03-05-2018"); //dd-mm-yyyy
console.log(d.getMonth()+2);
I need to understand how to do date formattting in javascript.
i have date as,
var date="12/02/1994";// dd/mm/yyy
var date1=new Date(date);
date1.getDate();// this gives me Month which is 02
date1.getMonth();// this gives me date which is 12.
How do i get the exact date i have in var date in get date and getmonth function? Please help
The answer is pretty simple: JavaScript uses mm/dd/yyyy data format.
It doesn't support dd/mm/yyyy format, so, if you need to parse this format, then you will have to do this manually like this:
function parseDdmmyyyy(str)
{
var spl = str.split('/');
return new Date(spl[2], spl[1] - 1, spl[0]);
}
or you will have to use external libraries like Moment.js.
Javascript date() expects date in mm/dd/yy and not in dd/mm/yy. And months start from 0 and not 1.
var from = "12/02/1994".split("/");
var date1 = new Date(from[2], from[1] - 1, from[0]);
date1.getDate();
date1.getMonth();
Use new Date('02/12/1994'), new Date('1994-02-12') or new Date(1994, 02-1, 12), because in js months start from 0 and american date format is used where month goes first
you can use the simple JS file DateFormat.js which has some very good example through the URL mattkruse (Date Funtion)
from this JS file you can validate the incoming date is a true format even you can add format date within a several ways.
Presumably you want to know how to format strings so they are consistently parsed by browsers. The short answer, is there is no guarantee that any particular string will be correctly parsed by all browsers in use (or perhaps even most).
So the bottom line is: don't parse strings with the Date constructor, ever. It's largely implementation dependent and even the one format specified in ES5 and ECMAScript 2015 is poorly and inconsistently supported.
How browsers treat a string like "12/02/1994" is entirely implementation dependent, however most will treat it as the peculiar US month/day/year format, i.e. 2 December and getMonth will return 11, since months are zero indexed.
So you should always manually parse strings (a library can help, but a simple parsing function is only 2 lines, 3 if validation is required), e.g.
// Parse a date string as d/m/y
// If s is not a valid date, return a Date object with its
// time value set to NaN.
function parseDMY(s) {
var b = s.split(/\D/);
var d = new Date(b[2], --b[1], b[0]);
return d && b[1] == d.getMonth()? d : new Date(NaN);
}
document.write(parseDMY('12/02/1994'));
so, i need format JSON date from this format
"9/30/2010 12:00:00 AM", it is MM/DD/YYYY HH:MM:SS to format like this : DD/MM/YYYY, so i dont need info about hours, min and sec, and i need replace months and days from json, i tried some different ways but it always failed
i need do this using jQuery
also i didnt find any answer to formating this date type, all i found was formating date like this :/Date(1224043200000)/
so anyone have idea?
you can create a Date Object from a string like so:
var myDate = new Date(dateString);
then you can manipulate it anyway you want, one way to get your desired output is:
var output = myDate.getDate() + "\\" + (myDate.getMonth()+1) + "\\" + myDate.getFullYear();
you can find more at this elated.com article "working with dates"
Unfortunately your "from" dateformat is not the one which is implementation-independent in JavaScript. And all the other formats depends on the implementation, which means even if this format would be understood by most of the implementation I/you can't be sure for example how the DD and MM order would be parsed (I am almost sure it would be local regional settings dependent). So I would recommend to use a 3rd party (or your hand written) date parser to get a Date object out of your input string. One such parser you can find here:
http://www.mattkruse.com/javascript/date/
Because your question is not 100% clear for me, it's possible that you have your date in the format of /Date(number)/ which suggests that you are calling an ASP.Net service from your jQuery code. In this case during the JSON parse you can convert it to a Date object:
data = JSON.parse(data, function (key, value) {
// parsing MS serialized DateTime strings
if (key == '[NAME_OF_DATE_PROPERTY_IN_THE_JSON_STRING]') {
return new Date(parseInt(value.replace("/Date(", "").replace(")/", ""), 10));
// maybe new Date(parseInt(value.substr(6))) also works and it's simpler
}
return value;
});
The code below solved my problem:
var date = new Date(parseInt(d.data[i].dtOrderDate.replace("/Date(", "").replace(")/", ""), 10));
var day = date.getDate();
var monthIndex = date.getMonth();
var year = date.getFullYear();
Try something like this :
var date = new Date(parseInt(jsonDate.substr(6)));
where jsonDate is variable that stores your date
I have astring directly coming form the database and I am creating object of Date as
Date dt=Date("23.03.2010") and it is comin NaN
whereas when I use Date dt= Date("03/23/2010") it works fine.
Any Idea how I can get this working?.
You can parse the string from the database and then create the date object. You will have to subtract 1 from the parsed month value to get a correct date.
var dateString = "23.03.2010";
var dateParts = dateString.split(".");
var dt = new Date(dateParts[2], dateParts[1] - 1, dateParts[0]);
You must pass string (parsed) dates in MDY format. This is to prevent ambiguity (does 5/6/2010 mean 6th May or 5th June?)
If you prefer, you can use new Date(year, month, day) format, and pass the arguments separately.
The safest way if is you can return the date as milliseconds since 1970-01-01, then you can easily create a Date object from it. Example:
var n = 1269302400000;
var dt = new Date(n);
Note that you'll want to invoke Date with the new operator - from the Mozilla Developer Center:
Invoking Date in a non-constructor
context (i.e., without the new
operator) will return a string
representing the current time.
The same page details the syntax of the Date constructor.
If you are constructing a Date from a string the format accepted is governed by the rules of the Date.parse method. See Microsoft's Date.parse documentation for a summary of these rules.
Give this a try...
var dateParts = '23.03.2010'.split('.');
// -1 from month because javascript months are 0-based
var dateObj = new Date(dateParts[2], dateParts[1]-1, dateParts[0]);
try
d="23.03.2010".split(".");
Date dt=Date([d[1],d[0],d[2]].join("/"))
i think it isn't the most beautiful way.