Convert a date to Date.now() like format in iavascript - javascript

I need to convert a date to "Date.now()" like format in javascript. For eg. using Date.now(), I'm getting the value as 1395150601449. I need my date to be formatted like this. How can I achieve this ? I would like to create a custom filter in angularjs for this formatting.
Any help will be highly appreciated.

Call the .getTime() function.
var d = new Date();
console.log(d.getTime());
You can do the opposite by passing such a timestamp to the Date constructor. Thus, to make a copy of a date instance:
var copy = new Date( d.getTime() );

Related

Javascript turn <c:out value into date

I am trying to turn my <c: out value into a Javascript date but when I try it I am constantly getting invalid date. This the string that I am trying to turn into a Javascript dateTime.
24-02-2021 17:34:27
I am getting this value by doing the following:
var d = ('<c:out value="${post.end}"/>');
And then I try changing it into a date by the following code:
var date1 = new Date(d);
console.log(date1);
And this is where I am getting the invalid date
Invalid Date
Now I'm not sure if this was because I have time at the end of the string, so I've also tried removing the time at the end by using substring to have the date string as:
24-02-2021
But yet this still has the same error. I have also replaced all the - with / so the date appears like this:
24/02/2021
What can I do to make sure that this date is a 'valid' date so I can use it within my code.
Your date string format is wrong. Please see the MDN reference for the Date built-in object.
You could do something like this:
d = d.split(' ')[0] // '24-02-2021'
const [day, month, year] = d.split('-')
const date1 = new Date(year, month, day)

Add time to string data/time

I am trying to pass a time stamp to my API that comes in the format of YYYY-MM-DD HH:MM:SS but i need to manipulate the time to add 5 hours.
Have I done something wrong here? Do I need to convert it to a JavaScript date first?
var manDate = "2020-08-16 16:15:00"
manDate.setHours(manDate.getHours() + 5);
data.manDate = manDate
console.log(manDate)
Expected output - 2020-08-16 21:15:00
When you create a var for date, you need to add the 'new Date()' method.
var manDate = new Date("2020-08-16 16:15:00");
manDate.setHours(manDate.getHours() + 5);
console.log(manDate.getHours());
And to log the hours use getHour() again in the log statement.
Use simpleDateFormat to format the date, then cast the formatted date to calendar and add hours to it.
Try with below code.
SimpleDateFormat sdfObj = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
sdfObj.parse("2020-08-16 16:15:00");
Calendar calendar = sdfObj.getCalendar();
calendar.add(Calendar.HOUR_OF_DAY, 5);
The question was asked to give a solution in java earlier. Below is the answer as per java.
Date newDate = DateUtils.addHours(oldDate, 5);

How to convert into Date time

When the date is passed from my c# to JavaScript it returns the date time as {4/3/2020 12:00:00 AM}
but in JavaScript it is shown as 1585852200000.
What is the format that is being used? And how can i convert it back?
You need to convert the Unix timestamp to DateTime format,
var localDate = new Date(1585852200000).toLocaleDateString("en-US")
console.log(localDate); // only local date
var localTime = new Date(1585852200000).toLocaleTimeString("en-US")
console.log(localTime) // only local time
// local datetime
console.log(new Date(1585852200000).toLocaleString());
1585852200000 is epoch date.
you can convert it as
var date = new Date(1585852200000)
console.log(new Date(1585852200000));
As an alternative from Shivaji's answer:
When you are passing the date through to JS you could cast it as a string with DateTime.ToString("dd/MM/yyyy") seen here on MSDN.
This will keep its integrity visually, if it is just for display purposes, otherwise you will need to re-cast appropriately in JS (in which case use Shivaji's answer).
JavaScript Date's object will return the DATE object and it's POSITION that is being assigned in your computer. So, when you are working with a date or datetime types, you can use some of the methods that are provided by the Date object, such as getDate() and getDay(). But, a better solution would be to format the Date object itself. For example: use the toString() or toUTCString() methods.
var d = new Date();
document.getElementById("demo").innerHTML = d.toString();
Reference:
https://www.w3schools.com/js/js_date_formats.asp
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

How to add days to current date in angular

Using this:
var myDate = new Date(new Date().getTime()+(5*24*60*60*1000));
I get a date and time like this 2018-12-30T14:15:08.226Z, but only i want is this 2018-12-30. How can I retrieve just the date?
**This is Fixed. Thank You everyone who helps!!!
You're experiencing a JS problem, it has nothing to do with Angular.
This will use Date methods to get all the data you want:
const date = new Date ();
let dateString = `${date.getFullYear()}-${date.getMonth()}-${date.getDate()}`;
// 2018-12-26
You can take advantage of the fact that the ISO 8601 format (what you are getting by implicitely converting to string) is well-codified with a separator T between the date and time in order to split it.
toISOString() gives you what you're seeing. split("T") splits the string into an array of strings with T as separator. [0] then extracts the first element.
var myDate = new Date(new Date().getTime()+(5*24*60*60*1000));
console.log(myDate.toISOString().split("T")[0]);

How to create object of Date("23.03.2010")

I have astring directly coming form the database and I am creating object of Date as
Date dt=Date("23.03.2010") and it is comin NaN
whereas when I use Date dt= Date("03/23/2010") it works fine.
Any Idea how I can get this working?.
You can parse the string from the database and then create the date object. You will have to subtract 1 from the parsed month value to get a correct date.
var dateString = "23.03.2010";
var dateParts = dateString.split(".");
var dt = new Date(dateParts[2], dateParts[1] - 1, dateParts[0]);
You must pass string (parsed) dates in MDY format. This is to prevent ambiguity (does 5/6/2010 mean 6th May or 5th June?)
If you prefer, you can use new Date(year, month, day) format, and pass the arguments separately.
The safest way if is you can return the date as milliseconds since 1970-01-01, then you can easily create a Date object from it. Example:
var n = 1269302400000;
var dt = new Date(n);
Note that you'll want to invoke Date with the new operator - from the Mozilla Developer Center:
Invoking Date in a non-constructor
context (i.e., without the new
operator) will return a string
representing the current time.
The same page details the syntax of the Date constructor.
If you are constructing a Date from a string the format accepted is governed by the rules of the Date.parse method. See Microsoft's Date.parse documentation for a summary of these rules.
Give this a try...
var dateParts = '23.03.2010'.split('.');
// -1 from month because javascript months are 0-based
var dateObj = new Date(dateParts[2], dateParts[1]-1, dateParts[0]);
try
d="23.03.2010".split(".");
Date dt=Date([d[1],d[0],d[2]].join("/"))
i think it isn't the most beautiful way.

Categories