Get user defined date String from javascript date object - javascript

I have a javascript Date object as below
var d = new Date();
console.log(d); //2019-11-28T04:27:43.268Z
I want this date to be formatted according to the user preference
Eg:
d-m-y : 28-11-2019
m-y-d : 11-2019-28
y-d-m : 2019-28-11
...... etc
Is there any way to do this in javascript without manually format the date(using regex or something else)?
Note: In Java I can achieve this by using DateFormat class format(Date date) method from the JDK

You can use Day.js API for easy conversion functions on date parameters.
Day.js
formatting DateTime
Day.js objects are formatted with the format() function.
Day.js github Link

Related

Weird ISO formatted Datestring to Javascript Date

I've got a Datestring like this one: 20171010T022902.000Z and I need to create Javascript Date from this string. new Date('20171010T022902.000Z') would return Invalid Date.
I saw that it's possible to use moment.js for this purpose but I am not sure how I would specify the according format for my given example. I found this example from another thread:
var momentDate = moment('1890-09-30T23:59:59+01:16:20', 'YYYY-MM-DDTHH:mm:ss+-HH:mm:ss');
var jsDate = momentDate.toDate();
Question:
How can I create a JavaScript date from a given Datestring in this format: 20171010T022902.000Z (using moment)?
Your input (20171010T022902.000Z) matches known ISO 8601 so you can simply use moment(String) parsing method. In the Supported ISO 8601 strings section of the docs you will find:
20130208T080910.123 # Short date and time up to ms
Then you can use toDate() method
To get a copy of the native Date object that Moment.js wraps
Your code could be like the following
var m = moment('20171010T022902.000Z');
console.log( m.format() );
console.log( m.toDate() );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
Note that this code does not shows Deprecation Warning (cited in Bergi's comment) because you input is in ISO 8601 known format. See this guide to know more about this warning.
Moreover "By default, moment parses and displays in local time" as stated here so format() will show the local value for your UTC input (20171010T022902.000Z ends with Z). See moment.utc(), utc() and Local vs UTC vs Offset guide to learn more about moment UTC mode.
I think you can do this without moment.js,.
Basically extract the parts you need using regex's capture groups, and then re-arrange into a correct format for new Date to work with.
var dtstr = '20171010T022902.000Z';
var dt = new Date(
dtstr.replace(/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(\.\d{3}Z)$/,
"$1-$2-$3T$4:$5:$6$7"));
console.log(dt);
console.log(dt.toString());
If you are using moment.js anyway, this should work ->
var dt = moment("20171010T022902.000Z", "YYYYMMDDTHHmmss.SSSSZ");
console.log(dt.toString());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.min.js"></script>

Working with date formats in Java and MySQL

Ok this is really bugging me.
I am developing a web app and I need to work with dates. When a date is displayed in a view, or whenever a date is entered into a form I need the format to be dd/mm/yyyy.
What data type do I choose for my SQL database columns which contain dates. 'Date' doesn't seem to work, do I use varchar?
But If I use varchar how do I use java script to perform arithmetic with dates.
Do I do some conversions server-side?
Please advise the best practices.
Also Im using laravel if theres any useful stuff already built in.
Date is the correct type to use in SQL DB.
To access the value use ISO date format "YYYY-MM-DD HH:mm:ss" .
You can create it from Java Date Object by using toISOString() method.
For easier time format conversion I can also recommend to check out Moment.js.
Best practice to save the date in MySQL table as date field only. Which saves the date string in YYYY-MM-DD HH:mm:ss format.
You need to make sure the following things.
Before inserting date into MySQL change the format of date string to YYYY-MM-DD HH:mm:ss.
When you retrieve the date from database convert the date string from YYYY-MM-DD HH:mm:ss to your desired format.
You can use SimpleDateFormat class in Java to convert the dates
format. Use format() function to format the date in desired and
parse() function to get the Java date object from string.
Reference: https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
You should use varchar2 in mysql.
You can retrieve that varchar type date in javascript and create date object.
var d=dbdate;
var date = new Date(d);
And you can perform all javascript functions on date.
Hope it will help.
Javascript Date() object supports separate entries of date by:
var date=new Date();
var y=date.getFullYear();//4 digits
var m=date.getMonth()+1;//0-11 digits, plus 1 for true state
var d=date.getDate();//1-31
var dateSQL=y+'-'+m+'-'+d;//i.e 2016-07-25
you can use MySQL filed as datetime and also insert datetime format but when you will show then process it as you want as like
when you insert value in table then you can also format it as like
<?php $mysqltime = date ("Y-m-d H:i:s", $phptime); ?>
where $phptime is your input variable
$str = suppose $row['date'] (mysql filed value)
date("d/m/Y", strtotime($str));
where $str your retrieve date filed

JavaScript: Get date format from culture settings

I want to get Date format from my defined culture settings using JavaScript.
My Culture is defined in Web.config File as:
<globalization culture="en-GB" uiCulture="en-GB"/>
I am getting the defined Culture through
CultureInfo culture = System.Globalization.CultureInfo.CurrentUICulture;
and i am passing it to my client. And at Client side I am using momemt.js library to parse my json date in to actual date format.
var date = moment(JsonDate).toDate().toLocaleDateString(myCulture); //"en-GB"
and I am getting the date in the required date format as "16/07/2016"
but I also want to get this Format as dd/MM/yyyy so that I can use this culture date format in my html (for date picker).
Please let me know how can I get this date format using culture info at client side.
You can use AngularJS-s date filter
check this link please - https://docs.angularjs.org/api/ng/filter/date
You may install moment.js in your project. https://momentjs.com/
Include moment-with-locales.min.js in your HTML template.
In your JavaScript:
moment.locale(myCulture);
var date = moment(JsonDate).format('L')

Compare ISO date without time stamp in javascript

I am querying data using OData, url looks like http://myurl.com/api/Customer?$filter=ResDate eq DateTime'2014-03-15T12:01:55.123'.
I'm getting date/time from jquery.datepicker instead of the static date and using moment.js to convert from DD-MM-YYYY to YYYY-MM-DDTHH:mm:ss in order to pass it to web service.
function convertDateToISOdate(date){
var newDate = moment(date,'DD-MM-YYYY').format('YYYY-MM-DDTHH:mm:ss');
return newDate;
}
Date returns from the function, is 2014-03-15T00:00:00.
Problem : 2014-03-15T12:01:55.123 is not equal to 2014-03-15T00:00:00, so there's no record selected.
What I want is , just to compare the date , not include time stamp.
Note : I can not change the format date/time at server side(Web service) because it's not belongs to me.
Any idea is much appreciated.
Your first call to moment(date,'DD-M-YYYY') is stripping the time information from the incoming data. try using moment(date) (no format) instead because momentjs recognizes your incoming date format intrinsically, without having to be told which format to use, and will correctly parse the H:M:S data, too.
MomentJS date parse information

format datestring based on locale without creating Date object (JavaScript)

I have a date string which looks like this: 2013-04-06T14:15:00
I'm looking for functions similar to toLocaleDateString()
(documentation). However, those functions don't take a String parameter; you need to create a Date object first. I'm trying to avoid timezones altogether, so does anyone know of a function (standard or from a plugin) which can format a datestring using a specific locale's rules (1/17/2013 vs 17/1/2013 etc.) using only my datestring?
I'm currently using jQuery, and this plugin for formatting dates: jQuery.dateFormat
Pass your date string to the Date constructor. It parses most legitimate formats.
new Date("1/17/2013")
new Date("2013-04-06T14:15:00")

Categories