Convert date to end of day - javascript

I get time in milliseconds from the server. I convert it to Date and get -
Mon Jul 22 2013 11:16:01 GMT+0200 (W. Europe Daylight Time) as the date in the record.
I want to separate out data of Monday, Tuesday etc into arrays. I am thinking of converting this date to Mon Jul 22 2013 23:59:59 GMT+0200 (W. Europe Daylight Time) and then filter out the records.
How can i change the date to the required end of the day time? or is there an easier way to do this ?

You could always construct a new DateTime object just using the year, month and day properties from the existing date, like so:
var actualDate = new Date(); // 2013-07-30 17:11:00
var endOfDayDate = new Date(actualDate.getFullYear()
,actualDate.getMonth()
,actualDate.getDate()
,23,59,59); // 2013-07-30 23:59:59

For future visitors, just use
var start = new Date();
var end = new Date();
start.setHours(0,0,0,0);
end.setHours(23,59,59,999);

Using http://momentjs.com:
var now = new Date().getTime();
var endOfDay = moment(now).endOf("day").toDate(); // Wed Jan 20 2016 23:59:59 GMT-0800 (PST)

var actualDate = new Date()
var eodDate = new Date(Math.floor(actualDate.getTime()/86400000+1)*86400000 + actualDate .getTimezoneOffset()*60000 - 1000)
where 86400000 are total milliseconds in a day

If two Date Objects are on the same day then they have the same Date String:
new Date('1374488161000').toDateString()
=> "Tue Jul 30 2013"
new Date('13744917610403').toDateString()
=> "Tue Jul 30 2013"
Although a rather naive method of comparing days, it's probably the simplest comparison.

Related

What type of date strings are these in JS?

I get a date string as Fri Sep 17 2021 11:50:59 GMT-0400 (Eastern Daylight Time) from one place. I get it from 2021-09-17T11:50:59-04:00 in a second place.
I want to convert the first format to the second.
I am doing this in a crazy way, so I am thinking there must be a better one.
var d = new Date(`Fri Sep 17 2021 11:50:59 GMT-0400 (Eastern Daylight Time)`);
var iso = d.toISOString();
var time = d.toTimeString();
console.log(iso);
console.log(time);
var [date] = iso.split('T')
var [,localTime, timezone] = time.match(/([^ ]+) GMT([^ ]+)/);
var timezoneWithColon = timezone.replace(/(-*[0-9]{2,2})([0-9]{2,2})/,"$1:$2")
var desiredFormat = '2021-09-17T11:50:59-04:00';
var convertedFormat = `${date}T${localTime}${timezoneWithColon}`;
console.log(desiredFormat)
console.log(convertedFormat)
console.log(desiredFormat === convertedFormat);
The fiddle is over at https://jsfiddle.net/Dave_Stein/8tLv2g4j/.
2021-09-17T11:50:59-04:00 is an ISO-8601 date string.
toISOString should work, however it will convert the time to UTC. If you want this to format in your current timezone, you'll have to use a library such as date-fns:
import { formatISO } from 'date-fns'
formatISO(new Date(`Fri Sep 17 2021 11:50:59 GMT-0400 (Eastern Daylight Time)`))
// prints '2021-09-17T11:50:59-04:00'

How to convert string date-time range to javascript date objects?

I have a date-time range string that looks like this.
2019-06-14, 12:00:00 AM - 2019-06-15, 12:00:00 AM
2019-06-14, 12:00:00 AM is the start date.
2019-06-15, 12:00:00 AM is the end date.
I want to convert this string into two javascript date objects named "startdate" and "enddate".
How do i do that? I am comfortable using moment.js as well, so a solution with moment.js will also work for me.
Thanks!
Try this code below
function getStartAndEndDate( dateStr ){
let dates = dateStr.split( " - " );
let start = new Date( dates[0] );
let end = new Date( dates[1] );
return{ startDate: start, endDate: end };
}
Usage:
getStartAndEndDate( "2019-06-14, 12:00:00 AM - 2019-06-15, 12:00:00 AM" );
Output
{startDate: Fri Jun 14 2019 00:00:00 GMT-0500 (Central Daylight Time), endDate: Sat Jun 15 2019 00:00:00 GMT-0500 (Central Daylight Time)}
The best way to do this is using new Date()
Example:
var stringDate = '2019-06-14, 12:00:00 AM '
var startDate = new Date(stringDate)
console.log(startDate)
var stringDate2 = '2019-06-15, 12:00:00 AM'
var finishDate = new Date(stringDate2)
console.log(finishDate)

Javascript:String to date fails

I want to convert a date, given as yyyy-mm-ddThh:mm:ss to a Javascript Date.
First attemp:
var str = "2013-10-31T18:15:30";
var date = new Date(str)
Returns Thu Oct 31 2013 18:15:30 GMT+0100 (CET).
Second attemp:
var str = "2013-10-31T18:15:30";
var str_parts = str.split("T");
var date_parts = str_parts[0].split("-");
var time_parts = str_parts[1].split(":");
var date = new Date(date_parts[0], date_parts[1], date_parts[2], time_parts[0], time_parts[1], time_parts[2]);
Returns Sun Dec 01 2013 18:15:30 GMT+0100 (CET). Do I miss something? Shouldn't this also return Thu Oct 31 2013 18:15:30 GMT+0100 (CET)? Somehow, the date is incorrect, while the time fits.
The corresponding fiddle: http://jsfiddle.net/4CLAj/2/
In the Date constructor Date(year,month,day,hour,minute,second) the month is zero-based, i.e. January is zero.
So for the second attempt:
var date = new Date(date_parts[0], Number(date_parts[1]) - 1, date_parts[2], time_parts[0], time_parts[1], time_parts[2]);
See http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf section 15.9.1.4

JSP and JavaScript convert date

I have a problem while trying to convert a specific type of date.
My goal is to get it into this format: dd/MM/yyyy
The current date format: Thu Apr 04 00:00:00 EEST 2013
When I alerted using JavaScript, it responds that it is not a date. I used many solutions like to format it on JSP:
<fmt:formatDate value="${theDate}" pattern="dd/MM/yyyy"/>
Result error:
Attempt to convert String "Thu Apr 04 00:00:00 EEST 2013" to type "java.util.Date", but there is no PropertyEditor for that type.
And even in Javascript:
var dateCreation = new Date(theDate);
The problem in JavaScript is that it says that dateCreation is not a date. Any ideas?
Problem with your date string "Thu Apr 04 00:00:00 EEST 2013"
when i tried with your date string got IllegelArgumentException
change "Thu Apr 04 00:00:00 EEST 2013" to "Thu Apr 04 00:00:00 EST 2013" then working fine.
I'm unable to guess why you got that EEST (one E extra).
public static void main(String[] args) {
Date date = new Date("Thu Apr 04 00:00:00 EST 2013");
System.out.println(date);
}
You are getting error in javascript because your passing the same string to JS i guess.
fmt:formatDate expects a java date object as value. In your case looks like theDate is not a date object but a String representation of date object. Please provide a date object and that should work.
Also in JavaScript what is the value of theDate param and where is it defined?
The date object in JavaScript has the following constructors:
var d = new Date();
var d = new Date(milliseconds); // from epoch
var d = new Date(dateString); // "yyyy-mm-dd hh:mm:ss"
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
Make sure you use one of them. Bear in mind that the month is 0-based for the last mentioned constructor.
EST is GMT-05:00 while EEST is GMT+03:00. The difference occurs e.g. when parsing "Thu Apr 04 23:00:00 EEST 2013". Java (7) can parse EEST, but it can not format in EEST.
String s = "Thu Apr 04 23:00:00 EEST 2013";
SimpleDateFormat sdfParse = new SimpleDateFormat("E MMM d H:m:s z yyyy", Locale.ENGLISH);
Date d = sdfParse.parse(s);
SimpleTimeZone stz = new SimpleTimeZone(3 * 3600000 /* GMT+03:00 */, "EEST");
GregorianCalendar cal = new GregorianCalendar(stz, Locale.ENGLISH);
cal.setTime(d);
String ddmmyyyy = String.format("%02d/%02d/%4d", cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR));
System.out.println(s+"\n"+ddmmyyyy);
In JavaScript:
function format2(s) {s="0"+s;return s.substr(s.length-2);}
function dateFormat(theDate) {
//theDate = "Thu Apr 04 00:00:00 EEST 2013";
var timestamp = Date.parse(theDate.replace(/EEST/, "GMT+0300"));
var datePseudoGMT = new Date(timestamp+3 * 3600000);
var dateCreation = format2(datePseudoGMT.getUTCDate())
+"/"+format2(datePseudoGMT.getUTCMonth()+1)
+"/"+format2(datePseudoGMT.getUTCFullYear());
console.log(dateCreation);
return dateCreation;
}

Format date time JavaScript

How to format date and time like this in JavaScript ?
March 05, 2012 # 14:30 (UTC - 9:30)
I use this code to calculate EST time :
function getDate() {
var now = new Date();
var utc = now.getTime() + (now.getTimezoneOffset() * 60000);
return new Date(utc + (3600000 * -4));
}
I use the date-time-format that Tats recommended because doing it manually is a huge PIA.
var yourDate = dateFormat(getDate(), "mmmm dd, yyyy # HH:MM) + "(UTC -9:30)";
Keep in mind this isn't Daylight Savings aware.. and you are asking for UTC -9:30 in your format, but your function converts to -4. Also, I believe that now.getTime returns in UTC.. so you can just add your difference there.
JavaScript Date Format
Check out date.js! It's a really powerful little library for working with Dates in JavaScript.
To get today's date in EST, you can do something like...
var today = new Date();
today.toString(); // outputs "Wed Apr 11 2012 15:40:40 GMT-0500 (CDT)"
today.setTimezone("EST");
today.toString(); // outputs "Wed Apr 11 2012 14:40:40 GMT-0500 (CDT)"
Also, its worth mentioning to checkout moment.js. I think the two libraries complement each other.
If you do just
var now = new Date();
document.write(now);
you will get
Wed Mar 14 2012 20:53:06 GMT+0000 (GMT Standard Time)
Link1, Link2.
Is it what you want?

Categories