adding one day to my date [duplicate] - javascript
I'm working with a date in this format: yyyy-mm-dd.
How can I increment this date by one day?
Something like this should do the trick:
String dt = "2008-01-01"; // Start date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(dt));
c.add(Calendar.DATE, 1); // number of days to add
dt = sdf.format(c.getTime()); // dt is now the new date
UPDATE (May 2021): This is a really outdated answer for old, old Java. For Java 8 and above, see https://stackoverflow.com/a/20906602/314283
Java does appear to be well behind the eight-ball compared to C#. This utility method shows the way to do in Java SE 6 using the Calendar.add method (presumably the only easy way).
public class DateUtil
{
public static Date addDays(Date date, int days)
{
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, days); //minus number would decrement the days
return cal.getTime();
}
}
To add one day, per the question asked, call it as follows:
String sourceDate = "2012-02-29";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date myDate = format.parse(sourceDate);
myDate = DateUtil.addDays(myDate, 1);
java.time
On Java 8 and later, the java.time package makes this pretty much automatic. (Tutorial)
Assuming String input and output:
import java.time.LocalDate;
public class DateIncrementer {
static public String addOneDay(String date) {
return LocalDate.parse(date).plusDays(1).toString();
}
}
I prefer to use DateUtils from Apache. Check this http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/time/DateUtils.html. It is handy especially when you have to use it multiple places in your project and would not want to write your one liner method for this.
The API says:
addDays(Date date, int amount) : Adds a number of days to a date returning a new object.
Note that it returns a new Date object and does not make changes to the previous one itself.
SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd" );
Calendar cal = Calendar.getInstance();
cal.setTime( dateFormat.parse( inputString ) );
cal.add( Calendar.DATE, 1 );
Construct a Calendar object and call add(Calendar.DATE, 1);
Java 8 added a new API for working with dates and times.
With Java 8 you can use the following lines of code:
// parse date from yyyy-mm-dd pattern
LocalDate januaryFirst = LocalDate.parse("2014-01-01");
// add one day
LocalDate januarySecond = januaryFirst.plusDays(1);
Take a look at Joda-Time (https://www.joda.org/joda-time/).
DateTimeFormatter parser = ISODateTimeFormat.date();
DateTime date = parser.parseDateTime(dateString);
String nextDay = parser.print(date.plusDays(1));
Please note that this line adds 24 hours:
d1.getTime() + 1 * 24 * 60 * 60 * 1000
but this line adds one day
cal.add( Calendar.DATE, 1 );
On days with a daylight savings time change (25 or 23 hours) you will get different results!
you can use Simple java.util lib
Calendar cal = Calendar.getInstance();
cal.setTime(yourDate);
cal.add(Calendar.DATE, 1);
yourDate = cal.getTime();
Date today = new Date();
SimpleDateFormat formattedDate = new SimpleDateFormat("yyyyMMdd");
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, 1); // number of days to add
String tomorrow = (String)(formattedDate.format(c.getTime()));
System.out.println("Tomorrows date is " + tomorrow);
This will give tomorrow's date. c.add(...) parameters could be changed from 1 to another number for appropriate increment.
If you are using Java 8, then do it like this.
LocalDate sourceDate = LocalDate.of(2017, Month.MAY, 27); // Source Date
LocalDate destDate = sourceDate.plusDays(1); // Adding a day to source date.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); // Setting date format
String destDate = destDate.format(formatter)); // End date
If you want to use SimpleDateFormat, then do it like this.
String sourceDate = "2017-05-27"; // Start date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
calendar.setTime(sdf.parse(sourceDate)); // parsed date and setting to calendar
calendar.add(Calendar.DATE, 1); // number of days to add
String destDate = sdf.format(calendar.getTime()); // End date
Since Java 1.5 TimeUnit.DAYS.toMillis(1) looks more clean to me.
SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd" );
Date day = dateFormat.parse(string);
// add the day
Date dayAfter = new Date(day.getTime() + TimeUnit.DAYS.toMillis(1));
long timeadj = 24*60*60*1000;
Date newDate = new Date (oldDate.getTime ()+timeadj);
This takes the number of milliseconds since epoch from oldDate and adds 1 day worth of milliseconds then uses the Date() public constructor to create a date using the new value. This method allows you to add 1 day, or any number of hours/minutes, not only whole days.
In Java 8 simple way to do is:
Date.from(Instant.now().plusSeconds(SECONDS_PER_DAY))
It's very simple, trying to explain in a simple word.
get the today's date as below
Calendar calendar = Calendar.getInstance();
System.out.println(calendar.getTime());// print today's date
calendar.add(Calendar.DATE, 1);
Now set one day ahead with this date by calendar.add method which takes (constant, value). Here constant could be DATE, hours, min, sec etc. and value is the value of constant. Like for one day, ahead constant is Calendar.DATE and its value are 1 because we want one day ahead value.
System.out.println(calendar.getTime());// print modified date which is tomorrow's date
Thanks
startCalendar.add(Calendar.DATE, 1); //Add 1 Day to the current Calender
In java 8 you can use java.time.LocalDate
LocalDate parsedDate = LocalDate.parse("2015-10-30"); //Parse date from String
LocalDate addedDate = parsedDate.plusDays(1); //Add one to the day field
You can convert in into java.util.Date object as follows.
Date date = Date.from(addedDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
You can formate LocalDate into a String as follows.
String str = addedDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
With Java SE 8 or higher you should use the new Date/Time API
int days = 7;
LocalDate dateRedeemed = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/YYYY");
String newDate = dateRedeemed.plusDays(days).format(formatter);
System.out.println(newDate);
If you need to convert from java.util.Date to java.time.LocalDate, you may use this method.
public LocalDate asLocalDate(Date date) {
Instant instant = date.toInstant();
ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
return zdt.toLocalDate();
}
With a version prior to Java SE 8 you may use Joda-Time
Joda-Time provides a quality replacement for the Java date and time
classes and is the de facto standard date and time library for Java
prior to Java SE 8
int days = 7;
DateTime dateRedeemed = DateTime.now();
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/uuuu");
String newDate = dateRedeemed.plusDays(days).toString(formatter);
System.out.println(newDate);
Apache Commons already has this DateUtils.addDays(Date date, int amount) http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/time/DateUtils.html#addDays%28java.util.Date,%20int%29 which you use or you could go with the JodaTime to make it more cleaner.
Just pass date in String and number of next days
private String getNextDate(String givenDate,int noOfDays) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
String nextDaysDate = null;
try {
cal.setTime(dateFormat.parse(givenDate));
cal.add(Calendar.DATE, noOfDays);
nextDaysDate = dateFormat.format(cal.getTime());
} catch (ParseException ex) {
Logger.getLogger(GR_TravelRepublic.class.getName()).log(Level.SEVERE, null, ex);
}finally{
dateFormat = null;
cal = null;
}
return nextDaysDate;
}
If you want to add a single unit of time and you expect that other fields to be incremented as well, you can safely use add method. See example below:
SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
cal.set(1970,Calendar.DECEMBER,31);
System.out.println(simpleDateFormat1.format(cal.getTime()));
cal.add(Calendar.DATE, 1);
System.out.println(simpleDateFormat1.format(cal.getTime()));
cal.add(Calendar.DATE, -1);
System.out.println(simpleDateFormat1.format(cal.getTime()));
Will Print:
1970-12-31
1971-01-01
1970-12-31
Use the DateFormat API to convert the String into a Date object, then use the Calendar API to add one day. Let me know if you want specific code examples, and I can update my answer.
Try this method:
public static Date addDay(int day) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.DATE, day);
return calendar.getTime();
}
It's simple actually.
One day contains 86400000 milliSeconds.
So first you get the current time in millis from The System by usingSystem.currentTimeMillis() then
add the 84000000 milliSeconds and use the Date Class to generate A date format for the milliseconds.
Example
String Today = new Date(System.currentTimeMillis()).toString();
String Today will be 2019-05-9
String Tommorow = new Date(System.currentTimeMillis() + 86400000).toString();
String Tommorow will be 2019-05-10
String DayAfterTommorow = new Date(System.currentTimeMillis() + (2 * 86400000)).toString();
String DayAfterTommorow will be 2019-05-11
You can use this package from "org.apache.commons.lang3.time":
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date myNewDate = DateUtils.addDays(myDate, 4);
Date yesterday = DateUtils.addDays(myDate, -1);
String formatedDate = sdf.format(myNewDate);
If you are using Java 8, java.time.LocalDate and java.time.format.DateTimeFormatter can make this work quite simple.
public String nextDate(String date){
LocalDate parsedDate = LocalDate.parse(date);
LocalDate addedDate = parsedDate.plusDays(1);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-mm-dd");
return addedDate.format(formatter);
}
The highest voted answer uses legacy java.util date-time API which was the correct thing to do in 2009 when the question was asked. In March 2014, java.time API supplanted the error-prone legacy date-time API. Since then, it is strongly recommended to use this modern date-time API.
I'm working with a date in this format: yyyy-mm-dd
You have used the wrong letter for the month, irrespective of whether you are using the legacy parsing/formatting API or the modern one. The letter m is used for minute-of-hour and the correct letter for month-of-year is M.
yyyy-MM-dd is the default format of java.time.LocalDate
The java.time API is based on ISO 8601 standards and therefore it does not require specifying a DateTimeFormatter explicitly to parse a date-time string if it is already in ISO 8601 format. Similarly, the toString implementation of a java.time type returns a string in ISO 8601 format. Check LocalDate#parse and LocalDate#toString for more information.
Ways to increment a local date by one day
There are three options:
LocalDate#plusDays(long daysToAdd)
LocalDate#plus(long amountToAdd, TemporalUnit unit): It has got some additional capabilities e.g. you can use it to increment a local date by days, weeks, months, years etc.
LocalDate#plus(TemporalAmount amountToAdd): You can specify a Period (or any other type implementing the TemporalAmount) to add.
Demo:
import java.time.Instant;
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;
public class Main {
public static void main(String[] args) {
// Parsing
LocalDate ldt = LocalDate.parse("2020-10-20");
System.out.println(ldt);
// Incrementing by one day
LocalDate oneDayLater = ldt.plusDays(1);
System.out.println(oneDayLater);
// Alternatively
oneDayLater = ldt.plus(1, ChronoUnit.DAYS);
System.out.println(oneDayLater);
oneDayLater = ldt.plus(Period.ofDays(1));
System.out.println(oneDayLater);
String desiredString = oneDayLater.toString();
System.out.println(desiredString);
}
}
Output:
2020-10-20
2020-10-21
2020-10-21
2020-10-21
2020-10-21
How to switch from the legacy to the modern date-time API?
You can switch from the legacy to the modern date-time API using Date#toInstant on a java-util-date instance. Once you have an Instant, you can easily obtain other date-time types of java.time API. An Instant represents a moment in time and is independent of a time-zone i.e. it represents a date-time in UTC (often displayed as Z which stands for Zulu-time and has a ZoneOffset of +00:00).
Demo:
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Date;
public class Main {
public static void main(String[] args) {
Date date = new Date();
Instant instant = date.toInstant();
System.out.println(instant);
ZonedDateTime zdt = instant.atZone(ZoneId.of("Asia/Kolkata"));
System.out.println(zdt);
OffsetDateTime odt = instant.atOffset(ZoneOffset.of("+05:30"));
System.out.println(odt);
// Alternatively, using time-zone
odt = instant.atZone(ZoneId.of("Asia/Kolkata")).toOffsetDateTime();
System.out.println(odt);
LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneId.of("Asia/Kolkata"));
System.out.println(ldt);
// Alternatively,
ldt = instant.atZone(ZoneId.of("Asia/Kolkata")).toLocalDateTime();
System.out.println(ldt);
}
}
Output:
2022-11-12T12:52:18.016Z
2022-11-12T18:22:18.016+05:30[Asia/Kolkata]
2022-11-12T18:22:18.016+05:30
2022-11-12T18:22:18.016+05:30
2022-11-12T18:22:18.016
2022-11-12T18:22:18.016
Learn more about the modern Date-Time API from Trail: Date Time.
Let's clarify the use case: You want to do calendar arithmetic and start/end with a java.util.Date.
Some approaches:
Convert to string and back with SimpleDateFormat: This is an inefficient solution.
Convert to LocalDate: You would lose any time-of-day information.
Convert to LocalDateTime: This involves more steps and you need to worry about timezone.
Convert to epoch with Date.getTime(): This is efficient but you are calculating with milliseconds.
Consider using java.time.Instant:
Date _now = new Date();
Instant _instant = _now.toInstant().minus(5, ChronoUnit.DAYS);
Date _newDate = Date.from(_instant);
You can do this just in one line.
e.g to add 5 days
Date newDate = Date.from(Date().toInstant().plus(5, ChronoUnit.DAYS));
to subtract 5 days
Date newDate = Date.from(Date().toInstant().minus(5, ChronoUnit.DAYS));
Related
How to add days to javascript unix timestamp? [duplicate]
I want to convert date to timestamp, my input is 26-02-2012. I used new Date(myDate).getTime(); It says NaN.. Can any one tell how to convert this?
Split the string into its parts and provide them directly to the Date constructor: Update: var myDate = "26-02-2012"; myDate = myDate.split("-"); var newDate = new Date( myDate[2], myDate[1] - 1, myDate[0]); console.log(newDate.getTime());
Try this function, it uses the Date.parse() method and doesn't require any custom logic: function toTimestamp(strDate){ var datum = Date.parse(strDate); return datum/1000; } alert(toTimestamp('02/13/2009 23:31:30'));
this refactored code will do it let toTimestamp = strDate => Date.parse(strDate) this works on all modern browsers except ie8-
There are two problems here. First, you can only call getTime on an instance of the date. You need to wrap new Date in brackets or assign it to variable. Second, you need to pass it a string in a proper format. Working example: (new Date("2012-02-26")).getTime();
UPDATE: In case you came here looking for current timestamp Date.now(); //as suggested by Wilt or var date = new Date(); var timestamp = date.getTime(); or simply new Date().getTime(); /* console.log(new Date().getTime()); */
You need just to reverse your date digit and change - with ,: new Date(2012,01,26).getTime(); // 02 becomes 01 because getMonth() method returns the month (from 0 to 11) In your case: var myDate="26-02-2012"; myDate=myDate.split("-"); new Date(parseInt(myDate[2], 10), parseInt(myDate[1], 10) - 1 , parseInt(myDate[0]), 10).getTime(); P.S. UK locale does not matter here.
To convert (ISO) date to Unix timestamp, I ended up with a timestamp 3 characters longer than needed so my year was somewhere around 50k... I had to devide it by 1000: new Date('2012-02-26').getTime() / 1000
function getTimeStamp() { var now = new Date(); return ((now.getMonth() + 1) + '/' + (now.getDate()) + '/' + now.getFullYear() + " " + now.getHours() + ':' + ((now.getMinutes() < 10) ? ("0" + now.getMinutes()) : (now.getMinutes())) + ':' + ((now.getSeconds() < 10) ? ("0" + now .getSeconds()) : (now.getSeconds()))); }
For those who wants to have readable timestamp in format of, yyyymmddHHMMSS > (new Date()).toISOString().replace(/[^\d]/g,'') // "20190220044724404" > (new Date()).toISOString().replace(/[^\d]/g,'').slice(0, -3) // "20190220044724" > (new Date()).toISOString().replace(/[^\d]/g,'').slice(0, -9) // "20190220" Usage example: a backup file extension. /my/path/my.file.js.20190220
Your string isn't in a format that the Date object is specified to handle. You'll have to parse it yourself, use a date parsing library like MomentJS or the older (and not currently maintained, as far as I can tell) DateJS, or massage it into the correct format (e.g., 2012-02-29) before asking Date to parse it. Why you're getting NaN: When you ask new Date(...) to handle an invalid string, it returns a Date object which is set to an invalid date (new Date("29-02-2012").toString() returns "Invalid date"). Calling getTime() on a date object in this state returns NaN.
JUST A REMINDER Date.parse("2022-08-04T04:02:10.909Z") 1659585730909 Date.parse(new Date("2022-08-04T04:02:10.909Z")) 1659585730000
/** * Date to timestamp * #param string template * #param string date * #return string * #example datetotime("d-m-Y", "26-02-2012") return 1330207200000 */ function datetotime(template, date){ date = date.split( template[1] ); template = template.split( template[1] ); date = date[ template.indexOf('m') ] + "/" + date[ template.indexOf('d') ] + "/" + date[ template.indexOf('Y') ]; return (new Date(date).getTime()); }
The below code will convert the current date into the timestamp. var currentTimeStamp = Date.parse(new Date()); console.log(currentTimeStamp);
The first answer is fine however Using react typescript would complain because of split('') for me the method tha worked better was. parseInt((new Date("2021-07-22").getTime() / 1000).toFixed(0)) Happy to help.
In some cases, it appears that some dates are stubborn, that is, even with a date format, like "2022-06-29 15:16:21", you still get null or NaN. I got to resolve mine by including a "T" in the empty space, that is: const inputDate = "2022-06-29 15:16:21"; const newInputDate = inputDate.replace(" ", "T"); const timeStamp = new Date(newInputDate).getTime(); And this worked fine for me! Cheers!
It should have been in this standard date format YYYY-MM-DD, to use below equation. You may have time along with example: 2020-04-24 16:51:56 or 2020-04-24T16:51:56+05:30. It will work fine but date format should like this YYYY-MM-DD only. var myDate = "2020-04-24"; var timestamp = +new Date(myDate)
You can use valueOf method new Date().valueOf()
a picture speaks a thousand words :) Here I am converting the current date to timestamp and then I take the timestamp and convert it to the current date back, with us showing how to convert date to timestamp and timestamp to date.
The simplest and accurate way would be to add the unary operator before the date console.log(`Time stamp is: ${Number(+new Date())}`)
Answers have been provided by other developers but in my own way, you can do this on the fly without creating any user defined function as follows: var timestamp = Date.parse("26-02-2012".split('-').reverse().join('-')); alert(timestamp); // returns 1330214400000
Simply performing some arithmetic on a Date object will return the timestamp as a number. This is useful for compact notation. I find this is the easiest way to remember, as the method also works for converting numbers cast as string types back to number types. let d = new Date(); console.log(d, d * 1);
This would do the trick if you need to add time also new Date('2021-07-22 07:47:05.842442+00').getTime() This would also work without Time new Date('2021-07-22 07:47:05.842442+00').getTime() This would also work but it won't Accept Time new Date('2021/07/22').getTime() And Lastly if all did not work use this new Date(year, month, day, hours, minutes, seconds, milliseconds) Note for Month it the count starts at 0 so Jan === 0 and Dec === 11
+new Date(myDate) this should convert myDate to timeStamp
ERROR Error: InvalidPipeArgument: "12-01-2020 - 12-02-2020' to a date' for pipe 'DatePipe'
I am trying to concatenate two dates and assigning to variable but it is throwing an error ERROR Error: InvalidPipeArgument: 'Unable to convert “12-01-2020 - 13-02-2020” into a date' for pipe 'DatePipe'.where I am going wrong? dates which I am getting from backend is projectStartDate: "2020-12-21T13:55:00.000+00:00".I am converting it to 12-01-2020 / timestamp after that concatenating both and assigning to projectduration value. this.startDate = this.datepipe.transform(response.projectStartDate, 'yyyy-MM-dd','es-ES'); this.endDate = this.datepipe.transform(response.projectEndDate, 'yyyy-MM-dd','es-ES'); response.gbRFEbean.projectDuration.value = this.startDate + "-" +this.endDate ;
The Date format: DD-MM-YYYY is invalid. You can try using : new Date("12-01-2020") It will give Invalid Date in chrome dev tools. Solution You can change the date format to MM-DD-YYYY and then pass it to datepipe.transform let date = response.projectStartDate.replace(/(\d{2})-(\d{2})-(\d{4})/, "$2-$1-$3") this.startDate = this.datepipe.transform(date, 'yyyy-MM-dd','es-ES'); date = response.projectEndDate.replace(/(\d{2})-(\d{2})-(\d{4})/, "$2-$1-$3") this.endDate = this.datepipe.transform(date , 'yyyy-MM-dd','es-ES');
locale is the fourth argument of the DatePipe transform and timezone is the third argument. Currently you have the locale as the third argument. I'd probably configure your locale like this (and the date pipe will automatically work for your locale without specifying): Missing locale data for the locale "XXX" with angular transform takes either a javascript date or an ISO date string so I'm guessing your dates (projectStartDate, projectEndDate) are strings that aren't in the ISO format? The error message implies that one of those fields has the entire value of 12-01-2020 - 13-02-2020 sample code with ISO date string startDate = '2020-01-12'; endDate = '2020-02-13'; formattedStartDate = this.datePipe.transform(this.startDate); formattedEndDate = this.datePipe.transform(this.endDate); constructor(private datePipe: DatePipe) { console.log(`${this.formattedStartDate} - ${this.formattedEndDate}`); } Sample code with javascript date startDate = new Date('2020-01-12'); endDate = new Date('2020-02-13'); formattedStartDate = this.datePipe.transform(this.startDate, 'yyyy-MM-dd'); formattedEndDate = this.datePipe.transform(this.endDate, 'yyyy-MM-dd'); constructor(private datePipe: DatePipe) { console.log(`${this.formattedStartDate} - ${this.formattedEndDate}`); } If your dates are strings in a dd-MM-yyyy format, you can parse them with a library like luxon: npm i luxon And import import { DateTime } from 'luxon'; And parse startDate = DateTime.fromFormat("12-01-2020", "dd-MM-yyyy").toISODate(); As a final note it's a little funny to put the dates in an ISO date format (yyyy-MM-dd) and then format them in the same format. The pipe makes more sense, particularly with you app locale set, if you want to use formats such as mediumDate (the default) which might display 12 ene. 2020
convert string to UTC time using jquery
I am trying to convert string to time, the string i have are in this format, '8:3' and '16:45'. I want to convert UTC time in jQuery.
You can write your function to create UTC date with the time string. function toUTC(str) { let [h, m] = str.split(':'); let date = new Date(); date.setHours(h, m, 0) return date.toUTCString(); } console.log(toUTC('8:3')) console.log(toUTC('16:45'))
You don't need jQuery for such operations. Just the simple Date object will do the trick. Say you want to convert time from a specific date. let date = new Date('2020-04-01'); // leave the Date parameter blank if today date.setHours(16); // must be 24 hours format date.setMinutes(45); let theUTCFormat = date.getUTCDate(); Cheers,
Given a ISO 8601 date/time, how to use JS date() to get the day of the week (0-6)?
Given a datetime string like so: mystring = '2012-10-23T02:40:59Z' I need to be able to get the day of the week (0-6) from the string. How can I pass the above to JS so I can do something like so: var d = new Date(mystring); var n = d.getDay(); console.log(n) where n returns 0-6. Thank you
While the Date object should be able to parse the ISO 8601 format in ECMA-262, it does not work reliably across browsers so you are much better off to parse them manually: function isoStringToDate(s) { var b = s.split(/\D/); return new Date(Date.UTC(b[0], --b[1], b[2], b[3]||0, b[4]||0, b[5]||0, b[6]||0)); } You can then use the getDay method to get the day number (Sunday = 0, Saturday = 6): isoStringToDate('2012-10-23T02:40:59Z').getDay(); // 2 for me
Do what you proposed! Date - getDay() Returns the day of the week for the specified date according to local time.
How to set Date formate in javascript?
I want to convert datetime format for my radtime picker. I am getting 2012-8-2-13-00-00 as my output when I pick date from my radtime picker. When I try to convert in to date it is saying invalid date. The JavaScript: function SourqtyValidation() { var specifiedtime = document.getElementById('<%=txtSpecifiedArrvialTime.ClientID %>').value; alert(specifiedtime); var a = new Date(specifiedtime); var actuvalarrivaltime = document.getElementById('<%=txtActualArrivalTime.ClientID %>').value; alert(actuvalarrivaltime); var b = new Date(actuvalarrivaltime); b.format("dd/MM/yyyy hh:mm:ss"); alert(b); var difference =Math.round((a - b) / 1000); alert(difference); } The aspx: //txtSpecifiedArrvialTime = predifened as 2012/08/02 09:35:55; <telerik:RadTimePicker ID="txtActualArrivalTime" runat="server" EmptyMessage="Actual Arrival Time"> </telerik:RadTimePicker> So how can I get difference between two times in minutes?
to get the time difference,date should be in same format, "2012-8-2-13-00-00" is not the correct format, convert it into format of "2012/08/02 13:00:00" than you can get the differencein in second by dividing it to 1000. you can use this to convert your string to datetime var dt = '2012-8-2-13-00-00'.split(/\-|\s/); dat = new Date(dt.slice(0,3).reverse().join('/')+' '+dt[3]+':'+dt[4]+':'+dt[5]);
Try using Datejs it has very handy methods: Eg.: Date.parse('Thu, 1 July 2004 22:30:00'); Date.parseExact("10/15/2004", "M/d/yyyy"); // The Date of 15-Oct-2004 Very Good library for handling Data Time in javascript. Datejs is an open-source JavaScript Date Library. Datejs