datetime to timestamp javascript - javascript

i have this time format :
DateTime(2015, 5, 11, 12, 0, 0)
i would like to know if i can convert it into a time stamp.
i have made this convert function from ISO 8601 to Timestamp and i would like to know if i can adapt it to this time format :
var myDate = new Date("2017-07-31T15:30:00+0000");
var offset = myDate.getTimezoneOffset() * 60 * 1000;
var withOffset = myDate.getTime();
var withoutOffset = withOffset - offset;
console.log(myDate.getTimezoneOffset()*60 * 1000)
console.log('with Offset ' + withOffset);
console.log('without Offset (timeStamp of your timezone) ' +withoutOffset);

did you try
Date.parse(your date here)/1000
Date.parse(new Date(2015, 5, 11, 12, 0, 0))/1000

you can use the library momentjs to convert it.
Here you are assigning an instance of momentjs to CurrentDate:
var CurrentDate = moment();
Here just a string, the result from default formatting of a momentjs instance:
var CurrentDate = moment().format();
And here the number of seconds since january of... well, unix timestamp:
var CurrentDate = moment().unix();
momentjs guide

Parsing dates is a pain in JavaScript as there's no extensive native support. However you could do something like the following by relying on the Date(year, month, day [, hour, minute, second, millisecond]) constructor signature of the Date object.
var dateString = '17-09-2013 10:08',
dateTimeParts = dateString.split(' '),
timeParts = dateTimeParts[1].split(':'),
dateParts = dateTimeParts[0].split('-'),
date;
date = new Date(dateParts[2], parseInt(dateParts[1], 10) - 1, dateParts[0], timeParts[0], timeParts[1]);
console.log(date.getTime()); //1379426880000
console.log(date); //Tue Sep 17 2013 10:08:00 GMT-0400

Related

add 12 months for Now Date

Hi, I would like to add 12 months and subtract 1 day for my current
date.
Example :
valStartDate :2018-01-20
expected_date:2019-01-19
I try below code but error "getFullYear() not a function to allow"
this.endDate =this.valStartDate.getFullYear()+1+'-'+this.valStartDate.getMonth()+'-'+(this.valStartDate.getDate()-1);
Ensure that your given start date is a date and not a string.
var startDate = new Date(2018, 0, 20);
var startDatePlus12Months = new Date(startDate.setMonth(startDate.getMonth() + 12));
var expectedDate = new Date(startDatePlus12Months.getFullYear(), startDatePlus12Months.getMonth(), startDatePlus12Months.getDate() - 1);
Here is a method of abstracting the date you want, apply this the variable and you should be good to go.
var date = new Date(); // now
var newDate = new Date(date.getFullYear() + 1, date.getMonth(), date.getDate() - 1);
console.log(newDate.toLocaleDateString());
this.valStartDate.getFullYear() In order for this to work, this.valStartDate must be a valid javascript date and look the same format as new Date(); would give you.
Fri Apr 26 2019 11:52:15 GMT+0100 (British Summer Time)
this.endDate = new Date(this.endDate); // <= maybe you get a string date...
this.endDate.setMonth(this.endDate.getMonth() + 12);
this.endDate.setDate(this.endDate.getDate() - 1);
If you're getting your date from a server or from a previous Json format, maybe you need to convert it from string to Date first: this.endDate = new Date(this.endDate);. It seems this is your case.
This is easy with the help of Moment.js:
const startDate = moment('2018-01-20');
const endDate = startDate.add(12, 'months').subtract(1, 'days').toDate();

How to convert an ISO date to the date format yyyy-mm-dd?

How can I get a date having the format yyyy-mm-dd from an ISO 8601 date?
My 8601 date is
2013-03-10T02:00:00Z
How can I get the following?
2013-03-10
Just crop the string:
var date = new Date("2013-03-10T02:00:00Z");
date.toISOString().substring(0, 10);
Or if you need only date out of string.
var strDate = "2013-03-10T02:00:00Z";
strDate.substring(0, 10);
Try this
date = new Date('2013-03-10T02:00:00Z');
date.getFullYear()+'-' + (date.getMonth()+1) + '-'+date.getDate();//prints expected format.
Update:-
As pointed out in comments, I am updating the answer to print leading zeros for date and month if needed.
date = new Date('2013-08-03T02:00:00Z');
year = date.getFullYear();
month = date.getMonth()+1;
dt = date.getDate();
if (dt < 10) {
dt = '0' + dt;
}
if (month < 10) {
month = '0' + month;
}
console.log(year+'-' + month + '-'+dt);
You could checkout Moment.js, Luxon, date-fns or Day.js for nice date manipulation.
Or just extract the first part of your ISO string, it already contains what you want.
Here is an example by splitting on the T:
"2013-03-10T02:00:00Z".split("T")[0] // "2013-03-10"
And another example by extracting the 10 first characters:
"2013-03-10T02:00:00Z".substr(0, 10) // "2013-03-10"
This is what I do to get date only:
let isoDate = "2013-03-10T02:00:00Z";
alert(isoDate.split("T")[0]);
let isoDate = "2013-03-10T02:00:00Z";
var d = new Date(isoDate);
d.toLocaleDateString('en-GB'); // dd/mm/yyyy
d.toLocaleDateString('en-US'); // mm/dd/yyyy
Moment.js will handle date formatting for you. Here is how to include it via a JavaScript tag, and then an example of how to use Moment.js to format a date.
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
moment("2013-03-10T02:00:00Z").format("YYYY-MM-DD") // "2013-03-10"
Moment.js is pretty big library to use for a single use case. I recommend using date-fns instead. It offers basically the most functionality of Moment.js with a much smaller bundle size and many formatting options.
import format from 'date-fns/format'
format('2013-03-10T02:00:00Z', 'YYYY-MM-DD'); // 2013-03-10, YYYY-MM-dd for 2.x
One thing to note is that, since it's the ISO 8601 time format, the browser generally converts from UTC time to local timezone. Though this is simple use case where you can probably do '2013-03-10T02:00:00Z'.substring(0, 10);.
For more complex conversions date-fns is the way to go.
UPDATE: This no longer works with Firefox and Chromium v110+ (Feb 2023) because the 'en-CA' locale now returns the US date format.
Using toLocaleDateString with the Canadian locale returns a date in ISO format.
function getISODate(date) {
return date.toLocaleDateString('en-ca');
}
getISODate(new Date()); // '2022-03-24'
To all who are using split, slice and other string-based attempts to obtain the date, you might set yourself up for timezone related fails!
An ISO-String has Zulu-Timezone and a date according to this timezone, which means, it might use a date a day prior or later to the actual timezone, which you have to take into account in your transformation chain.
See this example:
const timeZoneRelatedDate = new Date(2020, 0, 14, 0, 0);
console.log(timeZoneRelatedDate.toLocaleDateString(
'ja-JP',
{
year: 'numeric',
month: '2-digit',
day: '2-digit'
}
).replace(/\//gi,'-'));
// RESULT: "2020-01-14"
console.log(timeZoneRelatedDate.toISOString());
// RESULT: "2020-01-13T23:00:00.000Z" (for me in UTC+1)
console.log(timeZoneRelatedDate.toISOString().slice(0,10));
// RESULT: "2020-01-13"
Use:
new Date().toISOString().substring(0, 10);
This will output the date in YYYY-MM-DD format:
let date = new Date();
date = date.toISOString().slice(0,10);
The best way to format is by using toLocaleDateString with options
const options = {year: 'numeric', month: 'numeric', day: 'numeric' };
const date = new Date('2013-03-10T02:00:00Z').toLocaleDateString('en-EN', options)
Check Date section for date options here https://www.w3schools.com/jsref/jsref_tolocalestring.asp
Pass your date in the date object:
var d = new Date('2013-03-10T02:00:00Z');
d.toLocaleDateString().replace(/\//g, '-');
If you have a date object:
let date = new Date()
let result = date.toISOString().split`T`[0]
console.log(result)
or
let date = new Date()
let result = date.toISOString().slice(0, 10)
console.log(result)
To extend on rk rk's solution: In case you want the format to include the time, you can add the toTimeString() to your string, and then strip the GMT part, as follows:
var d = new Date('2013-03-10T02:00:00Z');
var fd = d.toLocaleDateString() + ' ' + d.toTimeString().substring(0, d.toTimeString().indexOf("GMT"));
A better version of answer by #Hozefa.
If you have date-fns installed, you could use formatISO function
const date = new Date(2019, 0, 2)
import { formatISO } from 'date-fns'
formatISO(date, { representation: 'date' }) // '2019-01-02' string
If you have the timezone you can do:
const myDate = "2022-10-09T18:30:00.000Z"
const requestTimezone = "Asia/Calcutta";
const newDate = new Date(myDate).toLocaleString("en-CA", {
dateStyle: "short",
timeZone: requestTimezone,
});
console.log(newDate)
>> 2022-10-10
Another outputs:
const myDate = "2022-10-02T21:00:00.000Z"
const requestTimezone = "Asia/Jerusalem";
>> 2022-10-03
const myDate = "2022-09-28T04:00:00.000Z"
const requestTimezone = "America/New_York";
>> 2022-09-28
I used this:
HTMLDatetoIsoDate(htmlDate){
let year = Number(htmlDate.toString().substring(0, 4))
let month = Number(htmlDate.toString().substring(5, 7))
let day = Number(htmlDate.toString().substring(8, 10))
return new Date(year, month - 1, day)
}
isoDateToHtmlDate(isoDate){
let date = new Date(isoDate);
let dtString = ''
let monthString = ''
if (date.getDate() < 10) {
dtString = '0' + date.getDate();
} else {
dtString = String(date.getDate())
}
if (date.getMonth()+1 < 10) {
monthString = '0' + Number(date.getMonth()+1);
} else {
monthString = String(date.getMonth()+1);
}
return date.getFullYear()+'-' + monthString + '-'+dtString
}
Source: http://gooplus.fr/en/2017/07/13/angular2-typescript-isodate-to-html-date/
var d = new Date("Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time)");
alert(d.toLocaleDateString());
let dt = new Date('2013-03-10T02:00:00Z');
let dd = dt.getDate();
let mm = dt.getMonth() + 1;
let yyyy = dt.getFullYear();
if (dd<10) {
dd = '0' + dd;
}
if (mm<10) {
mm = '0' + mm;
}
return yyyy + '-' + mm + '-' + dd;
Many of these answers give potentially misleading output if one is looking for the day in the current timezone.
This function will output the day corresponding with the date's timezone offset:
const adjustDateToLocalTimeZoneDayString = (date?: Date) => {
if (!date) {
return undefined;
}
const dateCopy = new Date(date);
dateCopy.setTime(dateCopy.getTime() - dateCopy.getTimezoneOffset()*60*1000);
return dateCopy.toISOString().split('T')[0];
};
Tests:
it('return correct day even if timezone is included', () => {
// assuming the test is running in EDT timezone
// 11:34pm eastern time would be the next day in GMT
let result = adjustDateToLocalTimeZoneDayString(new Date('Wed Apr 06 2022 23:34:17 GMT-0400'));
// Note: This is probably what a person wants, the date in the current timezone
expect(result).toEqual('2022-04-06');
// 11:34pm zulu time should be the same
result = adjustDateToLocalTimeZoneDayString(new Date('Wed Apr 06 2022 23:34:17 GMT-0000'));
expect(result).toEqual('2022-04-06');
result = adjustDateToLocalTimeZoneDayString(undefined);
expect(result).toBeUndefined();
});
Misleading approach:
To demonstrate the issue with the other answers' direct ISOString().split() approach, note how the output below differs from what one might expect:
it('demonstrates how the simple ISOString().split() may be misleading', () => {
// Note this is the 7th
expect(new Date('Wed Apr 06 2022 23:34:17 GMT-0400').toISOString().split('T')[0]).toEqual('2022-04-07');
});
Simpler way to get Year Or Month
let isoDateTime = "2013-03-10T02:00:00Z";
console.log(isoDateTime.split("T")[0]); //2013-03-10
Using Split Method
console.log(isoDateTime.split("-")[0]); //2013
console.log(isoDateTime.split("-")[1]); //03
WARNING: Most of these answers are wrong.
That is because toISOString() always returns the UTC date, not local date. So, for example, if your UTC time is 0500 and your timezone is GMT-0800, the day returned by toISOString() will be the UTC day, which will be one day ahead of the local timezone day.
You need to first convert the date to the local date.
const date = new Date();
date.setTime(date.getTime() - date.getTimezoneOffset()*60*1000)
Now date.toISOString() will always return the proper date according to the local timezone.
But wait, there's more. If we are also using toTimeString() that will now be wrong because time is now local and toTimeString() assumes it is UTC and converts it. So we need to first extract toTimeString() as a variable before doing the conversion.
The Date() class in javascript is inconsistent because of this and should really be updated to avoid this confusion. The toISOString() and toTimeString() methods should both do the same default things with respect to timezone.
Use the below code. It is useful for you.
let currentDate = new Date()
currentDate.toISOString()

compare 2 dates by combining date and time

var dateStart = $('input[id=orderdate-0]').val();
var timeStart = $('input[id=ordertime-0]').val();
var dateEnd = $('input[id=orderdate-1]').val();
var timeEnd = $('input[id=orderime-1]').val();
var startDate = new Date(dateStart + " " + timeStart);
var endDate = new Date(dateEnd + " " + timeEnd);
startDate.getTime();
alert(startDate);
i am trying to combine dateStart which is '2013-12-11' and timeStart which is '11:00' and trying to generate date out of it. But i get alert like invalid date. Is there anything wrong in code.?
The Date constructor is very particular about the date string formats it accepts.
Examples:
Dec 25, 1995
Wed, 09 Aug 1995 00:00:00
2011-10-10T14:48:00 (JavaScript 1.8.5+)
There is another constructor that take in the individual components of the date. If you break up your date strings into components you can use the following:
new Date(year, month, day, hour, minute);
Use moment JS plugin http://momentjs.com/
It's a date library for parsing, validating, manipulating, and formatting dates.
That is not a valid format for the parse function, you can use this instead:
var arr = dateStart.split('-');
var timeArr = timeStart.split(':');
new Date(arr[0], arr[1] -1, arr[2], timeArr[0] -1, timeArr[1] -1);
Read this.
Live DEMO

js date object based on strings

I want to make a js date object based on strings in format YYYYMMDD and HHMMSS.
function makeTimeStamp(myDate, MyTime){
// myDate format YYYYMMDD
// myTime format HHMMSS
var YYYY = myDate.substring(0, 3);
var MM = myDate.substring(4, 5);
var DD = myDate.substring(6,7);
var HH = myTime.substring(0,1);
var MM = myTime.substring(2,3);
var SS = myTime.substring(4,5);
jsDate =
}
If you meant to be creating a Date object for given year, month, day, hours, minutes and seconds, you can use new Date(year, month - 1, day, hours, minutes, seconds) to create a Date instance for it. Note that the month is 0 based, January is 0, February 1, etc. Hence the MM - 1;
function stringToDate(myDate, myTime){
// myDate format YYYYMMDD
// myTime format HHMMSS
var YYYY = myDate.substr(0, 4);
var MM = myDate.substr(4, 2);
var DD = myDate.substr(6, 2);
var HH = myTime.substr(0, 2);
var mm = myTime.substr(2, 2);
var SS = myTime.substr(4, 2);
var jsDate = new Date(YYYY, MM - 1, DD, HH, mm, SS);
return jsDate;
}
// returns a Date object for given date and time
var jsDate = stringToDate("20110818", "191500");
// returns 1313687700000
var timestamp = jsDate.getTime();
Note that I'm using string.substr(start_position, length) as you can easily see the length of the returned value.
You can try Date.js which is a date library. http://www.datejs.com/
You can convert those date and time formats in to ISO format pretty easily (e.g. "2011-08-18T12:34:56") and use a regular expression to make sure the arguments are formatted properly:
function makeTimestamp(myDate, myTime) {
var ds = myDate.match(/^(\d{4})(\d\d)(\d\d)$/)
, ts = myTime.match(/^(\d\d)(\d\d)(\d\d)$/);
if (!ds || !ts) { return null; }
return new Date(ds.slice(1,4).join("-") + "T" + ts.slice(1,4).join(":"));
}
var d = makeTimestamp('20110818', '123456');
d // => Fri Aug 19 2011 12:34:56 GMT-0400 (EDT)
you can try this: https://www.npmjs.com/package/timesolver
npm i timesolver
use it in your code:
const timeSolver = require('timeSolver');
const date = new Date();
const dateString = timeSolver.getString(date, 'YYYYMMDD HHMMSS');
`
You can get date string by using this method:
const dateString = timeSolver.getString(date, format);
Hope this will help you!

Concatenate a date and time value

i need to concatenate a date value and a time value to make one value representing a datetime in javascript.
thanks,
daniel
Working with strings is fun and all, but let's suppose you have two datetimes and don't like relying on strings.
function combineDateWithTime(d, t)
{
return new Date(
d.getFullYear(),
d.getMonth(),
d.getDate(),
t.getHours(),
t.getMinutes(),
t.getSeconds(),
t.getMilliseconds()
);
}
Test:
var taxDay = new Date(2016, 3, 15); // months are 0-indexed but years and dates aren't.
var clockout = new Date(0001, 0, 1, 17);
var timeToDoTaxes = combineDateWithTime(taxDay, clockout);
// yields: Fri Apr 15 2016 17:00:00 GMT-0700 (Pacific Daylight Time)
I could not make the accepted answer work so used moment.js
date = moment(selected_date + ' ' + selected_time, "YYYY-MM-DD HH:mm");
date._i "11-06-2014 13:30"
Assuming "date" is the date string and "time" is the time string:
// create Date object from valid string inputs
var datetime = new Date(date+' '+time);
// format the output
var month = datetime.getMonth()+1;
var day = datetime.getDate();
var year = datetime.getFullYear();
var hour = this.getHours();
if (hour < 10)
hour = "0"+hour;
var min = this.getMinutes();
if (min < 10)
min = "0"+min;
var sec = this.getSeconds();
if (sec < 10)
sec = "0"+sec;
// put it all togeter
var dateTimeString = month+'/'+day+'/'+year+' '+hour+':'+min+':'+sec;
Depending on the type of the original date and time value there are some different ways to approach this.
A Date object (which has both date and time) may be created in a number of ways.
birthday = new Date("December 17, 1995 03:24:00");
birthday = new Date(1995,11,17);
birthday = new Date(1995,11,17,3,24,0);
If the original date and time also is objects of type Date, you may use getHours(), getMinutes(), and so on to extract the desired values.
For more information, see Mozilla Developer Center for the Date object.
If you provide more detailed information in your question I may edit the answer to be more specific.

Categories

Resources