How to convert javascript string format to date - javascript

In my ajax success I am getting result.Date as "/Date(-2208967200000)/". I need to check with the following date and proceed..
How to convert the "/Date(-2208967200000)/" to "01-01-1900" for below if condition?
if (result.Date != "01-01-1900") {
....
}

You can convert result.Date into you comparison date format, same as below example
var dateString = "\/Date(-2208967200000)\/".substr(6);
var currentTime = new Date(parseInt(dateString ));
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var date = day + "/" + month + "/" + year;
After doing this.. you can compare it with other date..

Reference
var jsonDate = "/Date(-2208967200000)/";
var date = new Date(parseInt(jsonDate.substr(6)));
alert(date);
The substr function takes out the "/Date(" part, and the parseInt function gets the integer and ignores the ")/" at the end. The resulting number is passed into the Date constructor.
jQuery dateFormat is a separate plugin. You need to load that explicitly using a tag.

You could use a regex to get the value between the brackets and then pass that to the Date():
var input = "/Date(-2208967200000)/";
var matches = /\(([^)]+)\)/.exec(input);
var date = new Date(parseInt(matches[1], 10));
Example fiddle

Related

how to get UTC time in yyyyMMdd’T’HHmmss’Z’ fromat in javascript

I have tried this below
var dt = new Date();
utc = dt.toISOString();
console.log(utc)
which gives the result as such 2021-04-22T04:32:33.676Z
but I want this UTC DateTime in exactly yyyyMMdd’T’HHmmss’Z format...
As per my understanding, you don't want those extra dashes coming in the date string. You can simply remove them using replaceAll as below.
var dt = new Date();
utc = dt.toISOString().replaceAll('-', '');
The output will be 20210422T04:45:28.739Z
You can use moment.js library which allows string format to specify. It also supports lot more operations on dates.
var dt = moment();
console.log(dt.utc().format("YYYYMMDD[T]HHmmss[Z]"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
With your explanation, I think you want the date and time to be properly displayed in utc format right?
I think using toLocaleString() method will give you what you want.
var dt = new Date();
utc = dt.toLocaleString();
One approach using plain javascript would be
var dt = new Date();
function format(num) {
return num < 10 ? "0" + num : num;
}
console.log("" + dt.getUTCFullYear() + format(dt.getUTCMonth()) + format(dt.getUTCDate()) + "T" + format(dt.getUTCHours()) + format(dt.getUTCMinutes()) + format(dt.getUTCSeconds()) + "Z")
var dt = new Date();
dt.setMilliseconds(0);
utc = dt.toISOString().replace(/[-,.,:]/g,"").replace(/000Z/, "Z");
console.log(utc)

How to loop between dates that are in dmy format

Here is my 2 date
var startdate = '11-12-2016';
var stopdate = '13-12-2016';
I want to loop between these two dates. So, i did like this
var startMedicine = new Date(startdate);
var stopMedicine = new Date(stopdate);
while(startMedicine <= stopMedicine){
console.log(startdate)
}
But i am getting unlimited loops running in browser.
How can i do this.
Note :
I don't want to use jQuery for this one.
If the start and end date is same it should loop only once and the input date will be always d/m/y format. What is the mistake in my code. Pls help
Update :
I have mistaken the date format, my date format is d-m-y. How can i do this for one..
Increment date by one day per iteration using getDate
startdateArr = startdate.split('-');
stopdateArr = stopdate.split('-');
var startMedicine = new Date(startdateArr[2],startdateArr[1]-1,startdateArr[0]);
var stopMedicine = new Date(stopdateArr[2],stopdateArr[1]-1,stopdateArr[0]);
// thanks RobG for correcting on month index
while(startMedicine <= stopMedicine){
var v = startMedicine.getDate() + '-' + (startMedicine.getMonth() + 1) + '-' + startMedicine.getFullYear();
console.log(v);
startMedicine.setDate(startMedicine.getDate()+1);
}
In js month indexing starts at 0 so nov is 10 dec. is 11 and like so that's why i use getMonth() + 1
`
main problem is that you are not increasing your date.
here is the solution
var startdate = '11/12/2016';
var stopdate = '11/13/2016';
var startMedicine = new Date(startdate);
var stopMedicine = new Date(stopdate);
var currentMedicine = startMedicine;
var dayCount = 0;
while(currentMedicine < stopMedicine){
currentMedicine.setDate(startMedicine.getDate() + dayCount);
// You can replace '/' to '-' this if you want to have dd-mm-yyyy instead of dd/mm/yyy
var currentDate = currentMedicine.getDate() + '/' + (currentMedicine.getMonth() + 1) + '/' + currentMedicine.getFullYear(); // in dd/mm/yyyy format
console.log(currentDate);
dayCount++;
}
You can make use of moment js and moment js duration. Its for duration purpose only. It very easy and meant for same.

angularjs - calculate a date plus one day

I need to get the date one day after another date.
I do :
$scope.date2.setDate($scope.date1.getDate()+1);
if
$scope.date1 = 2015-11-27
then
$scope.date2 = 2015-11-28
It s ok,
but when
$scope.date1 = 2015-12-02
then
$scope.date2 = 2015-11-28 (ie tomorrow)
I don't understand why...
If anyone knows..
try this instead efficient simple pure JS
var todayDate = new Date();
console.log(new Date().setDate(todayDate.getDate()+1));
so you will have that same Date type object and hence you don't need to go with moment.js
Use moment.js for this momentjs
var startdate = "2015-12-02";
var new_date = moment(startdate, "YYYY-MM-DD").add('days', 1);
var day = new_date.format('DD');
var month = new_date.format('MM');
var year = new_date.format('YYYY');
alert(new_date);
alert(day + '.' + month + '.' + year);

convert DD/MMM/YYYY into a binary/epoch date javascript

Hi i am trying to convert dd/mmm/yyyy into a binary/epoch date.
example:
06/mar/2015
into
1425600000000
i build up my date
var Buildup = day + slash + month + slash + year;
but now i dont have a clue how to do it i have tried something like this:
var formattedDays = Buildup.split(" ")[0].split("-");
var epoch = new Date(formattedDays[0], formattedDays[1] - 1, formattedDays[2]).getSeconds;
var epochStart = new Date(formattedDays[0], formattedDays[1] - 1,formattedDays[2],formattedTime[0],formattedTime[1],formattedTime[2],0).getTime()/1000;
but no look?
like this :
var d = new Date('06/03/2015');
var n = d.getTime();
Date Documentation
GetTime Documentation

Add a variable number to a date in Java script

I have read a few articles but nothing seems to the point. I have created a form that records a reservation date (when a user wants to reserve a game) and the number of days they hope to borrow it for. I want to add this to the reservation date to get the date the game must be returned by. I have wrapped up my code so far into a function so that I can call it using an onclick method. What should this code look like to work properly? Almost forgot - to make life hard my date is written like this YYYY-MM-DD
function ReturnDate(){
var reservation_begin = document.getElementById('reservation_start').value;
var loan_period = document.getElementById('requested_days').value;
var reservation_end = document.getElementById('return_date');
var dateResult = reservation_begin + loan_period;
return_date.value = dateResult;
}
USING the Suggestions made by Linus
I made the following alterations but had trouble with the formatting of the return date. e.g Setting the reservation date to 2015-01-03 gave me the result of 2015-0-32 for the return date
function ReturnDate(){
var reservation_begin = document.getElementById('reservation_start').value;
var loan_period = document.getElementById('requested_days').value;
var resDate = new Date(reservation_begin);
alert(resDate)
var period = loan_period;
var output = document.getElementById('return_date');
resDate.setDate(resDate.getDate() + period);
alert(period)
//return_date.value = resDate.getFullYear() + "-" + (resDate.getMonth() + 1) + "-" + resDate.getDate();
return_date.value = resDate.getFullYear() + "-" + resDate.getMonth() + "-" + (resDate.getDate() +1);
}
As mentioned dates could be a bit tricky to handle with js.
But to just add days to a date this could be a solution?
JSBIN: http://jsbin.com/lebonababi/1/edit?js,output
JS:
var resDate = new Date('2015-02-01');
var period = 6;
var output = "";
resDate.setDate(resDate.getDate() + period);
output = resDate.getFullYear() + "-" + (resDate.getMonth() + 1) + "-" + resDate.getDate();
alert(output);
EDIT:
Added a new JSBin which is more consistent with the original code.
JSBin: http://jsbin.com/guguzoxuyi/1/edit?js,output
HTML:
<input id="reservationStart" type="text" value="2015-03-01" />
<br />
<input id="requestedDays" type="text" value="14" />
<br />
<a id="calculateDate" href="javascript:;">Calculate Date</a>
<br /><br /><br />
Output:
<input id="calculatedDate" type="text" />
JS:
// Click event
document.getElementById('calculateDate').addEventListener('click', returnDate);
// Click function
function returnDate(){
var reservationStart = document.getElementById('reservationStart').value,
requestedDays = parseInt(document.getElementById('requestedDays').value),
targetDate = new Date(reservationStart),
formattedDate = "";
// Calculate date
targetDate.setDate(targetDate.getDate() + requestedDays);
// Format date
formattedDate = formatDate(targetDate);
// Output date
document.getElementById('calculatedDate').value = formattedDate;
}
// Format date (XXXX-XX-XX)
function formatDate(fullDate) {
var dateYear = fullDate.getFullYear(),
dateMonth = fullDate.getMonth()+1,
dateDays = fullDate.getDate();
// Pad month and days
dateMonth = pad(dateMonth);
dateDays = pad(dateDays);
return dateYear + "-" + dateMonth + "-" + dateDays;
}
// Pad number
function pad(num) {
return (num < 10 ? '0' : '') + num;
}
As per my comment,
Split reservation_begin and use the Date constructor feeding in the
parts to create a Javascript date object. getTime will give you the
milliseconds since the Epoch. There are 86400000 milliseconds in a day, so
multiply this by loan_period. Add the two millisecond result together
and use the Date constructor with your total milliseconds to get
dateResult as a Javascript date object.
using Date.UTC but you don't have to.
function pad(num) {
return num < 10 ? '0' + num : num;
}
var reservation_begin = ('2015-02-01').split('-'),
loan_period = '5',
begin,
end;
reservation_begin[1] -= 1;
begin = new Date(Date.UTC.apply(null, reservation_begin)).getTime();
end = new Date(begin + 86400000 * loan_period);
document.body.textContent = [
end.getUTCFullYear(),
pad(end.getUTCMonth() + 1),
pad(end.getUTCDate())
].join('-');
Why split the date string into parts? This is to avoid cross browser parsing issues.
Why use milliseconds? This is the smallest value represented by Javascript Date, using this will avoid any rollover issues that may be present in browsers.
Why use UTC? You haven't specified the requirements for your script, and this is about as complex as it gets. You don't have to use it, you can just feed the parts into Date and use the non UTC get methods.
What does pad do? It formats the month values to MM and date values to DD.
Note that month is zero referenced in Javascript so months are represent by the numbers 0-11.
A bit confused with the third variable "reservation_end" but according to your question this solution might work.
var dateResult = new Date(reservation_begin);
dateResult.setDate(dateResult.getDate() + parseInt(loan_period));
alert(dateResult);
http://jsfiddle.net/uwfpbzt2/
Example using todays date:
var today = new Date();
today.setDate(today.getDate() + x);
where x is the number of days. Then just use getYear(), getMonth() and getDate() and format it how you like.
EDIT
var myDate = new Date(year, month, day, hours, minutes, seconds, milliseconds);
Assuming your date is entered in dd/mm/yyyy format as inputDate then
dateParts = inputDate.split("/");
var myDate = new Date(dateParts[2], dateParts[1]-1, dateParts[0]);
Depending on the date format your split() delimiter and array positions may be different but this is the general idea.

Categories