Save date 'without' time in JavaScript - javascript

At the moment I save my date like this: ISODate("2014-11-17T16:19:16.224Z"), but I want this result: ISODate("2014-11-16T23:00:00Z"). How can I do this?

An easier alternative is to use Date.setHours() - in single call you can set what you need - from hours to milliseconds. If you just want to get rid of the time.
var date = new Date();
date.setHours(0,0,0,0);
console.log ( date );

Set the parts you don't want saved to 0. In your example, you would set the minutes, seconds, and milliseconds to 0.
var date = new Date();
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
var isoDateString = date.toISOString();
console.log(isoDateString);

Or, a less verbose option:
var date = new Date();
var isoDateString = date.toISOString().substring(0,10);
console.log(isoDateString);

To Save a date without a time stamp:
let date = new Date().toLocaleDateString('en-US');
console.log(date)
// OUTPUT -> m/d/yyyy
Use this to find options to add as paramaters for the toLocaleDateString function

Related

Time changes after toLocaleTimeString()

I'm using a google sheets script, which on the click of a button will add values to two fields.
The first will contain the date, the second the time.
For this, I use this piece of code:
var timestamp = new Date();
var date = Utilities.formatDate(timestamp, "GMT+1", "dd/MM/yyyy");
var time = timestamp.toLocaleTimeString('nl-BE');
Now, the issue is that the time is off by 6 hours.
The timestamp value does contain the correct time, the date variable gets the correct date, but the time seems to differ 6 hours after the 'toLocaleTimeString() function.
Use Utilities.formatDate() for time as well, like this:
const timezone = SpreadsheetApp.getActive().getSpreadsheetTimeZone(); // or 'GMT+1'
const timestamp = new Date();
const dateString = Utilities.formatDate(timestamp, timezone, 'dd/MM/yyyy');
const timeString = Utilities.formatDate(timestamp, timezone, 'HH:mm:ss');
console.log(`date and time in ${timezone}: ${dateString} ${timeString}`);

javascript add 1ms to a string date

I have a var in js which is represented like so:
"lastTimeModified": "2019-02-26T11:38:20.222Z"
and I want to add to it 1ms
I have tried something like this:
dateObj = new Date();
dateObj.setMilliseconds(1);
var newDate = lastTimeModified + dateObj
but that doesn't seem to work.
If you can get your date in milliseconds than you can directly add 1 millisecond to it
var date = new Date(lastTimeModified) // convert string to date object
var mill = date.getMilliseconds() // Get millisecond value from date
mill += 1 // Add your one millisecond to it
date.setMilliseconds(mill) // convert millisecond to again date object
The below takes your time string turns it into a date object, gets the milliseconds since the 1. of January 1970 adds 1ms and turns it back into a date object
var newDate = new Date(new Date(lastTimeModified).getTime() + 1)

Remove Seconds/ Milliseconds from Date convert to ISO String

I have a date object that I want to
remove the miliseconds/or set to 0
remove the seconds/or set to 0
Convert to ISO string
For example:
var date = new Date();
//Wed Mar 02 2016 16:54:13 GMT-0500 (EST)
var stringDate = moment(date).toISOString();
//2016-03-02T21:54:13.537Z
But what I really want in the end is
stringDate = '2016-03-02T21:54:00.000Z'
There is no need for a library, simply set the seconds and milliseconds to zero and use the built–in toISOString method:
var d = new Date();
d.setSeconds(0,0);
document.write(d.toISOString());
Note: toISOString is not supported by IE 8 and lower, there is a pollyfil on MDN.
While this is easily solvable with plain JavaScript (see RobG's answer), I wanted to show you the Moment.js solution since you tagged your questions as "momentjs":
moment().seconds(0).milliseconds(0).toISOString();
This gives you the current datetime, without seconds or milliseconds.
Working example: http://jsbin.com/bemalapuyi/edit?html,js,output
From the docs: http://momentjs.com/docs/#/get-set/
A non-library regex to do this:
new Date().toISOString().replace(/.\d+Z$/g, "Z");
This would simply trim down the unnecessary part. Rounding isn't expected with this.
A bit late here but now you can:
var date = new Date();
this obj has:
date.setMilliseconds(0);
and
date.setSeconds(0);
then call toISOString() as you do and you will be fine.
No moment or others deps.
Pure javascript solutions to trim off seconds and milliseconds (that is remove, not just set to 0). JSPerf says the second funcion is faster.
function getISOStringWithoutSecsAndMillisecs1(date) {
const dateAndTime = date.toISOString().split('T')
const time = dateAndTime[1].split(':')
return dateAndTime[0]+'T'+time[0]+':'+time[1]
}
console.log(getISOStringWithoutSecsAndMillisecs1(new Date()))
function getISOStringWithoutSecsAndMillisecs2(date) {
const dStr = date.toISOString()
return dStr.substring(0, dStr.indexOf(':', dStr.indexOf(':')+1))
}
console.log(getISOStringWithoutSecsAndMillisecs2(new Date()))
This version works for me (without using an external library):
var now = new Date();
now.setSeconds(0, 0);
var stamp = now.toISOString().replace(/T/, " ").replace(/:00.000Z/, "");
produces strings like
2020-07-25 17:45
If you want local time instead, use this variant:
var now = new Date();
now.setSeconds(0, 0);
var isoNow = new Date(now.getTime() - now.getTimezoneOffset() * 60000).toISOString();
var stamp = isoNow.replace(/T/, " ").replace(/:00.000Z/, "");
Luxon could be your friend
You could set the milliseconds to 0 and then suppress the milliseconds using suppressMilliseconds with Luxon.
DateTime.now().toUTC().set({ millisecond: 0 }).toISO({
suppressMilliseconds: true,
includeOffset: true,
format: 'extended',
}),
leads to e.g.
2022-05-06T14:17:26Z
You can use the startOf() method within moment.js to achieve what you want.
Here's an example:
var date = new Date();
var stringDateFull = moment(date).toISOString();
var stringDateMinuteStart = moment(date).startOf("minute").toISOString();
$("#fullDate").text(stringDateFull);
$("#startOfMinute").text(stringDateMinuteStart);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.2/moment.js"></script>
<p>Full date: <span id="fullDate"></span></p>
<p>Date with cleared out seconds: <span id="startOfMinute"></span></p>
let date = new Date();
date = new Date(date.getFullYear(), date.getMonth(), date.getDate());
I hope this works!!
To remove the seconds and milliseconds values this works for me:
const date = moment()
// Remove milliseconds
console.log(moment.utc(date).format('YYYY-MM-DDTHH:mm:ss[Z]'))
// Remove seconds and milliseconds
console.log(moment.utc(date).format('YYYY-MM-DDTHH:mm[Z]'))
We can do it using plain JS aswell but working with libraries will help you if you are working with more functionalities/checks.
You can use the moment npm module and remove the milliseconds using the split Fn.
const moment = require('moment')
const currentDate = `${moment().toISOString().split('.')[0]}Z`;
console.log(currentDate)
Refer working example here:
https://repl.it/repls/UnfinishedNormalBlock
In case for no luck just try this code
It is commonly used format in datetime in the SQL and PHP
e.g.
2022-12-25 19:13:55
console.log(new Date().toISOString().replace(/^([^T]+)T([^\.]+)(.+)/, "$1 $2") )

Extract Month and Day in Javascript

I have the date in this format: 1347564203.713372
And need to end up with 2 variables, one that is the month from that date and another that is the day from that date.
How do I do this using Javascript/jQuery?
This should do:
var myDate = 1347564203.713372;
var d= new Date(myDate*1000);
var month = d.getMonth();
var day = d.getDate();
Create a Date object, use setTime to put your timestamp in there, then get the relevant parts:
var d = new Date(), t = 1347564203.713372;
d.setTime(t*1000); // JS uses timestamps in milliseconds
alert(d.getUTCDate());
alert(["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][d.getUTCMonth()]);
Note use of getUTC* functions - this helps avoid timezone issues and DST.

convert iso date to milliseconds in javascript

Can I convert iso date to milliseconds?
for example I want to convert this iso
2012-02-10T13:19:11+0000
to milliseconds.
Because I want to compare current date from the created date. And created date is an iso date.
Try this
var date = new Date("11/21/1987 16:00:00"); // some mock date
var milliseconds = date.getTime();
// This will return you the number of milliseconds
// elapsed from January 1, 1970
// if your date is less than that date, the value will be negative
console.log(milliseconds);
EDIT
You've provided an ISO date. It is also accepted by the constructor of the Date object
var myDate = new Date("2012-02-10T13:19:11+0000");
var result = myDate.getTime();
console.log(result);
Edit
The best I've found is to get rid of the offset manually.
var myDate = new Date("2012-02-10T13:19:11+0000");
var offset = myDate.getTimezoneOffset() * 60 * 1000;
var withOffset = myDate.getTime();
var withoutOffset = withOffset - offset;
console.log(withOffset);
console.log(withoutOffset);
Seems working. As far as problems with converting ISO string into the Date object you may refer to the links provided.
EDIT
Fixed the bug with incorrect conversion to milliseconds according to Prasad19sara's comment.
A shorthand of the previous solutions is
var myDate = +new Date("2012-02-10T13:19:11+0000");
It does an on the fly type conversion and directly outputs date in millisecond format.
Another way is also using parse method of Date util which only outputs EPOCH time in milliseconds.
var myDate = Date.parse("2012-02-10T13:19:11+0000");
Another option as of 2017 is to use Date.parse(). MDN's documentation points out, however, that it is unreliable prior to ES5.
var date = new Date(); // today's date and time in ISO format
var myDate = Date.parse(date);
See the fiddle for more details.
Yes, you can do this in a single line
let ms = Date.parse('2019-05-15 07:11:10.673Z');
console.log(ms);//1557904270673
Another possible solution is to compare current date with January 1, 1970, you can get January 1, 1970 by new Date(0);
var date = new Date();
var myDate= date - new Date(0);
Another solution could be to use Number object parser like this:
let result = Number(new Date("2012-02-10T13:19:11+0000"));
let resultWithGetTime = (new Date("2012-02-10T13:19:11+0000")).getTime();
console.log(result);
console.log(resultWithGetTime);
This converts to milliseconds just like getTime() on Date object
var date = new Date()
console.log(" Date in MS last three digit = "+ date.getMilliseconds())
console.log(" MS = "+ Date.now())
Using this we can get date in milliseconds
var date = new Date(date_string);
var milliseconds = date.getTime();
This worked for me!
if wants to convert UTC date to milliseconds
syntax : Date.UTC(year, month, ?day, ?hours, ?min, ?sec, ?milisec);
e.g :
date_in_mili = Date.UTC(2020, 07, 03, 03, 40, 40, 40);
console.log('miliseconds', date_in_mili);
In case if anyone wants to grab only the Time from a ISO Date, following will be helpful. I was searching for that and I couldn't find a question for it. So in case some one sees will be helpful.
let isoDate = '2020-09-28T15:27:15+05:30';
let result = isoDate.match(/\d\d:\d\d/);
console.log(result[0]);
The output will be the only the time from isoDate which is,
15:27

Categories

Resources