I have a ngbDatePicker which helps me to pick a date. Then it returns an object like this:
{year:2020,month:12,day:03}
I'd like to get an ISOString of this date with today's time(current). So if time is 18:42 I should be able to get something like this:
2020-12-03T18:42:00.000Z
To do that I parsed object and made date firstly
(model is the object holds date like above)
var date = new Date(this.model.year + "-" + this.model.month + "-" + this.model.day);
//then to add today's time I found solution below on the internet whcih didn't work for me
var date2 = new Date(date);
var isoDateTime = new Date(date2 .getTime() - (date2 .getTimezoneOffset() * 60000)).toISOString();
Here isoDateTime returns 2020-12-10T03:00:00.000Z which is not I want.
How to solve this?
Working stackblitz
Just take the time part of a Date object and combine it with this.model:
var date2 = new Date();
var date = new Date(this.model.year, this.model.month-1, this.model.day,
date2.getHours(), date2.getMinutes(), date2.getSeconds());
var isoDateTime = date.toISOString();
console.log(isoDateTime);
The month parameter is 0 based, so we have to substract 1 from the month.
Result (I chose Dec.1st 2020 in the Datepicker):
2020-12-01T19:22:42.000Z
Try on Stackblitz
You can create a single Date for the time and append it to values from the object:
function myISOString(obj) {
let z = n=>('0'+n).slice(-2);
return `${obj.year}-${z(obj.month)}-${z(obj.day)}T${new Date().toTimeString().substring(0,8)}`;
}
let obj = {year:2020, month:12, day: 3};
console.log(myISOString(obj));
PS the use of leading zeros like 03 for numbers should be avoided as once upon a time that notation indicated octal values (but not any more), so 09 might be confusing.
I need to get a date in this format:
2016-07-06T10:57Z
Using this code I have been able to get a date in a format somewhat like I need:
var isoDate = new Date().toISOString();
2016-07-06T08:46:08.127Z
But is there a way I can remove the seconds and fraction of seconds from the date so it appears exactly like the date: "2016-07-06T10:57Z" ?
You will always want to remove the last 8 characters ('Z' included) thus you can use a function like slice
isoDate = isoDate.slice(0, -8); //Remove seconds + fractions + Z
isoDate += "Z"; //Add back the Z
You can use this way because the format returned by toISOString() will always be
YYYY-MM-DDTHH:mm:ss.sssZ
Please try
var isoDate = new Date().toISOString();
var pos = isoDate.lastIndexOf(':');
var datePart1 = isoDate.substring(0,pos);
var datePart2 = isoDate.substr(-1, 1);
var dateStr = datePart1+datePart2;
console.log(dateStr);
I have the upload date for a course saved in a ViewModel variable #Model.Course.UploadDate when calling the following code:
alert('#Model.Course.UploadDate');
I get an output as expected of:
21/01/2014 16:16:13
I know want to check that the uploadDate is within the last 10 seconds before sending a statement to the database but trying to use the following code:
var uploadDate = new Date('#Model.Course.UploadDate.ToLongDateString()');
alert("UPLOAD DATE " + uploadDate);
I get an unexpected output of:
Tue Jan 21 2013 00:00:00 GMT+0000
This is the format that I need the date in only with the saved time data shown. I am then looking to perform a calculation as follows:
var TENSECONDS = 10 * 1000;
var uploadDate = new Date('#Model.Course.UploadDate.ToLongDateString()');
var today = new Date();
var check = today - uploadDate;
if (parseInt(check) > parseInt(TENSECONDS))
alert("ROUTE1");
else
alert("ROUTE2");
Quote from the documentation of the Date object constructor:
value: Integer value representing the number of milliseconds since 1
January 1970 00:00:00 UTC (Unix Epoch).
So actually that's the safest thing to pass to the constructor of a Date object instead of some strings which might be incorrectly interpreted and are completely culture dependent.
So just convert your DateTime instance to the number of milliseconds that elapsed since 1 January 1970 and feed this timestamp to the constructor:
var timestamp = #(Model.Course.UploadDate - new DateTime(1970, 1, 1)).TotalSeconds;
var uploadDate = new Date(timestamp);
As an alternative you could use the ISO8601 format if you intend to be passing a string:
dateString: String value representing a date. The string should be in
a format recognized by the Date.parse() method (IETF-compliant RFC
2822 timestamps and also a version of ISO8601).
So:
var uploadDate = new Date('#Model.Course.UploadDate.ToString("o")');
I solved this using the following code:
var dateArray = new Array();
dateArray = '#Model.Course.UploadDate'.split("/");
var dateD = dateArray[0];
var dateM = dateArray[1];
var dateY = dateArray[2];
var dateT = dateArray[3];
timeArray = dateT.split(":");
var timeH = timeArray[0];
var timeM = timeArray[1];
var timeS = timeArray[2];
var dateUS = dateM + "/" + dateD + "/" + dateY + dateT;
var uploadDate = new Date(dateD,dateM,dateY,timeH,timeM,timeS);
I am using AngularJS and we have a directive that uses a stored Regex to convert a bound value. So if I create this tag: <span ng-pattern="regex.Zip"></span> then Angular will reference the stored Regex and convert on the fly. I need a regex to format a date.
Example string:
2014-01-01T00:00:00.0000000
Desired output:
01/01/2014
BONUS desired output (if possible with regex alone)!:
01/01/2014 12:00am
This needs to be done with Javascript.
Using a regex :
var longdate = '2014-01-01T00:00:00.0000000';
var shortdate = longdate.replace(
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}).(\d{7})$/,
'$3/$2/$1'
);
console.log(shortdate); // 01/01/2014
Using the Date object :
This allow you to get the hour under 12h format.
var longdate = '2014-01-01T00:00:00.0000000';
var date = new Date(longdate);
var day = ('0' + date.getDate()).slice(-2); // add a leading 0
var mon = ('0' + date.getMonth()+1).slice(-2); // month go from 0 to 11
var yea = date.getFullYear();
var hou = ('0' + date.getUTCHours()%12).slice(-2); // back to 0 when we reach 12
var min = ('0' + date.getMinutes()).slice(-2);
var suf = date.getUTCHours() >= 12 ? 'pm' : 'am';
var shortdate = day+'/'+mon+'/'+yea+' '+hou+':'+min+suf;
console.log(shortdate); // 01/00/2014 00:00am
javascript code without regex
var d = new Date('2014-01-01T00:00:00.0000000');
var date = d.toLocaleDateString(); // 01/01/2014
Here's a solution with python.
from datetime import datetime
raw = '2014-01-01T00:00:00.0000000'
dt = datetime.strptime(raw, '%Y-%m-%dT%H:%M:%S.%f0')
print dt.strftime('%d/%m/%Y %H:%M%p')
I'm taking the string, changing it to a datetime object, then formatting it. It's very easy to get your head around it, check it out more here
i am trying to convert a string in the format dd-mm-yyyy into a date object in JavaScript using the following:
var from = $("#datepicker").val();
var to = $("#datepickertwo").val();
var f = new Date(from);
var t = new Date(to);
("#datepicker").val() contains a date in the format dd-mm-yyyy.
When I do the following, I get "Invalid Date":
alert(f);
Is this because of the '-' symbol? How can I overcome this?
Split on "-"
Parse the string into the parts you need:
var from = $("#datepicker").val().split("-")
var f = new Date(from[2], from[1] - 1, from[0])
Use regex
var date = new Date("15-05-2018".replace( /(\d{2})-(\d{2})-(\d{4})/, "$2/$1/$3"))
Why not use regex?
Because you know you'll be working on a string made up of three parts, separated by hyphens.
However, if you were looking for that same string within another string, regex would be the way to go.
Reuse
Because you're doing this more than once in your sample code, and maybe elsewhere in your code base, wrap it up in a function:
function toDate(dateStr) {
var parts = dateStr.split("-")
return new Date(parts[2], parts[1] - 1, parts[0])
}
Using as:
var from = $("#datepicker").val()
var to = $("#datepickertwo").val()
var f = toDate(from)
var t = toDate(to)
Or if you don't mind jQuery in your function:
function toDate(selector) {
var from = $(selector).val().split("-")
return new Date(from[2], from[1] - 1, from[0])
}
Using as:
var f = toDate("#datepicker")
var t = toDate("#datepickertwo")
Modern JavaScript
If you're able to use more modern JS, array destructuring is a nice touch also:
const toDate = (dateStr) => {
const [day, month, year] = dateStr.split("-")
return new Date(year, month - 1, day)
}
regular expression example:
new Date( "13-01-2011".replace( /(\d{2})-(\d{2})-(\d{4})/, "$2/$1/$3") );
Another possibility:
var from = "10-11-2011";
var numbers = from.match(/\d+/g);
var date = new Date(numbers[2], numbers[0]-1, numbers[1]);
Match the digits and reorder them
Using moment.js example:
var from = '11-04-2017' // OR $("#datepicker").val();
var milliseconds = moment(from, "DD-MM-YYYY").format('x');
var f = new Date(milliseconds)
Use this format: myDate = new Date('2011-01-03'); // Mon Jan 03 2011 00:00:00
var from = $("#datepicker").val();
var f = $.datepicker.parseDate("d-m-Y", from);
You can also write a date inside the parentheses of the Date() object, like these:
new Date("Month dd, yyyy hh:mm:ss")
new Date("Month dd, yyyy")
new Date(yyyy,mm,dd,hh,mm,ss)
new Date(yyyy,mm,dd)
new Date(milliseconds)
In my case
new Date("20151102034013".replace(/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/, "$1-$2-$3T$4:$5:$6"))
Result: Mon Nov 02 2015 04:40:13 GMT+0100 (CET)
then I use .getTime() to work with milliseconds
The accepted answer kinda has a bug
var from = $("#datepicker").val().split("-")
var f = new Date(from[2], from[1] - 1, from[0])
Consider if the datepicker contains "77-78-7980" which is obviously not a valid date. This would result in:
var f = new Date(7980, 77, 77);
=> Date 7986-08-15T22:00:00.000Z
Which is probably not the desired result.
The reason for this is explained on the MDN site:
Where Date is called as a constructor with more than one argument, if values are greater than their logical range (e.g. 13 is provided as the month value or 70 for the minute value), the adjacent value will be adjusted. E.g. new Date(2013, 13, 1) is equivalent to new Date(2014, 1, 1).
A better way to solve the problem is:
const stringToDate = function(dateString) {
const [dd, mm, yyyy] = dateString.split("-");
return new Date(`${yyyy}-${mm}-${dd}`);
};
console.log(stringToDate('04-04-2019'));
// Date 2019-04-04T00:00:00.000Z
console.log(stringToDate('77-78-7980'));
// Invalid Date
This gives you the possibility to handle invalid input.
For example:
const date = stringToDate("77-78-7980");
if (date === "Invalid Date" || isNaN(date)) {
console.log("It's all gone bad");
} else {
// Do something with your valid date here
}
You can use an external library to help you out.
http://www.mattkruse.com/javascript/date/source.html
getDateFromFormat(val,format);
Also see this: Parse DateTime string in JavaScript
You can just:
var f = new Date(from.split('-').reverse().join('/'));
let dateString = '13-02-2021' //date string in dd-mm-yyyy format
let dateArray = dateString.split("-");
//dateArray[2] equals to 2021
//dateArray[1] equals to 02
//dateArray[0] equals to 13
// using template literals below
let dateObj = new Date(`${dateArray[2]}-${dateArray[1]}-${dateArray[0]}`);
// dateObj equals to Sat Feb 13 2021 05:30:00 GMT+0530 (India Standard Time)
//I'm from India so its showing GMT+0530
P.S : Always refer docs for basics, MDN or DevDocs
Take a look at Datejs for all those petty date related issues.. You could solve this by parseDate function too
You could use a Regexp.
var result = /^(\d{2})-(\d{2})-(\d{4})$/.exec($("#datepicker").val());
if (result) {
from = new Date(
parseInt(result[3], 10),
parseInt(result[2], 10) - 1,
parseInt(result[1], 10)
);
}
new Date().toLocaleDateString();
simple as that, just pass your date to js Date Object